1

Assuming I have an array of base class pointers. Can I store a derived class object pointer (derived from that base class) in this array? and can I do it the other way around?

Akra
  • 265
  • 2
  • 10

2 Answers2

4

Can I store a derived class object pointer (derived from that base class) in this array?

Yes.

and can I do it the other way around?

No.

Say you have:

struct Base
{
};

struct Derived1 : Base
{
};

struct Derived2 : Base
{
};

std::vector<Derived1*> ptrs;
Base* bPtr = new Derived2;
ptrs.push_back(bPtr);        // Not allowed.
                             // If it were, imagine the problems.
                             // You have a Derived2* in the guise of a Derived1*
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Will I be able to do it even if the derived class has additional public functions? – Akra Jun 27 '16 at 16:11
  • 1
    You can. However, you cannot access the derived class members through the base class pointers. To access the derived class members, you'll have to cast the pointer back to the derived class pointer first. – R Sahu Jun 27 '16 at 16:14
3

You can indeed store a Derived* in an array of Base* (or any other data structure of Base pointers for that matter).

But the vice versa is not true as it violates the Liskov Substitution Principle.

Community
  • 1
  • 1
sjrowlinson
  • 3,297
  • 1
  • 18
  • 35