Akra
Akra

Reputation: 265

Can derived object pointers be stored in an array of base class pointers?

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?

Upvotes: 1

Views: 395

Answers (2)

sjrowlinson
sjrowlinson

Reputation: 3355

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.

Upvotes: 3

R Sahu
R Sahu

Reputation: 206607

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*

Upvotes: 4

Related Questions