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?
2 Answers
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*
2 Comments
Akra
Will I be able to do it even if the derived class has additional public functions?
R Sahu
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.
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.
Derived*in astd::vector<Base*>but not vice versa.Doginto an array ofAnimal, but you can't put anAnimalinto an array ofDog(no telling what that animal is)