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?
Asked
Active
Viewed 383 times
1
-
Why dont you make it a practical question by providing some code? – 463035818_is_not_an_ai Jun 27 '16 at 16:09
-
Because it is a theoretical question from a college exam and no code was provided. – Akra Jun 27 '16 at 16:10
-
1Yes you can store a `Derived*` in a `std::vector
` but not vice versa. – sjrowlinson Jun 27 '16 at 16:10 -
2Think of it like this: You can put a `Dog` into an array of `Animal`, but you can't put an `Animal` into an array of `Dog` (no telling what that animal is) – Krease Jun 27 '16 at 16:17
2 Answers
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
-
1You 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