-2

Let's say I have a base class Base:

class Base
{
}

And a derived classes Derived1

class Derived1: Base
{
    int a;
}

Now I have a vector:

std::vector<Base*>vec;

And let's say that I have appended this with a pointer to an instance of the derived class and I now want to access it's a member a. Let's also say that I know for a fact that the class I am converting is in fact Derived1 and not another derived class.

I have read other answers saying that casting the classes in the vector to the derived classes is bad idea, so I wish to avoid this. I also wish to avoid having to create a separate vector for each derived class, as this will get very messy after a while. If someone has suggestion that goes against my approach of the problem all together, but still allows me to manage many derived classes easily I would be glad to hear it.

Others have suggested using smart pointers in the vector, but I don't understand how this allows me to access members of the derived class. If this is a good approach I would appreciate if someone could explain it.

  • 2
    Make a `std::vector`, easy as that. No silly pointers, no casting, no confusion. – Kerrek SB Nov 30 '13 at 01:34
  • 1
    If you have a `Base*` and you *know* it is actually a `Derived*` (and need to treat it as such) then you have a design problem, so a cast is the least of your worries. Use virtual interfaces if you need polymorphism, and if you don't then you don't need a `Base*` either in the first place. – syam Nov 30 '13 at 01:58

1 Answers1

0

As you asked suggestion: Do not use:

std::vector<Base*>vec;

Rather do:

std::vector<Base>vec;

But more than that if you know vec will store Derived1 why it is not like:

std::vector<Derived1> vec;

Now if you dont do that, To access the member a you may do like:

for(auto iter = vec.begin();iter!=vec.end();iter++)
{
    Derived1* d = dynamic_cast<Derived*>(*iter);
    if(d!=NULL)
    {
        // do anything with d->a
    }
}
deeiip
  • 3,319
  • 2
  • 22
  • 33