-2

Im currrently having issues accessing a member of a child object when it is in a base vector, I know it is an object slicing issue, im trying to use dynamic casting but im a beginner and am not really sure on the syntax or how to use it, any help would be appreciated pseudocode:

class Base {}

Class Derived : public base {

bool A

}

std::vector<Base*> items;

Item* i = new Derived(constructor);

items.push_back(i);

// items[0]->A isnt accessible due to object slicing
CupidBlue
  • 3
  • 1
  • 1
    Use virtual getter and setter functions to access `A`. – πάντα ῥεῖ Jan 20 '21 at 00:06
  • 2
    Unrelated: This isn't because of object slicing. You still have a `Derived` at the pointer. Object slicing is when the derived class is stored as a base class, not merely referred to by a base class. – user4581301 Jan 20 '21 at 00:18
  • The default visibility for `class` in C++ is private. This isn't a slicing issue. It's a [visibility](https://en.cppreference.com/w/cpp/language/access) issue. – Silvio Mayolo Jan 20 '21 at 00:20
  • 1
    It's not slicing as @user4581301 but it's not solely due to visibility either. Even if `A` were a public member of `Derived`, you'd still have to dynamically cast a `Base*` pointer to a `Derived*` pointer before you could reach `A` through it. – Nathan Pierson Jan 20 '21 at 00:35
  • Why do you store it of type `Base` when you want to treat it as `Derived`? Especially without any check if it actually is of type `Derived`. Sounds like bad design to me. But if you need to, use [dynamic cast conversion](https://en.cppreference.com/w/cpp/language/dynamic_cast). – Aziuth Jan 20 '21 at 00:35
  • When setting up an inheritance hierarchy, Keep an eye on the [Liskov Substitution Principle](https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle). It will keep you out of a lot of trouble. – user4581301 Jan 20 '21 at 00:46

1 Answers1

0

First technique is to rely on virtual functions:

class Base 
{
    public:
    virtual int doStuff();
}

Class Derived : public base 
{
    public:
    virtual int doStuff();
}

Then, items[0]->doStuff() will call the derived version.

Second technique is to downcast:

dynamic_cast<Derived*>(items[0]);

This will give you either a nullptr or your Derived object pointer. Problem is, you'll need to ad a virtual function for this to work.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42