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?

4
  • Why dont you make it a practical question by providing some code? Commented Jun 27, 2016 at 16:09
  • Because it is a theoretical question from a college exam and no code was provided. Commented Jun 27, 2016 at 16:10
  • 1
    Yes you can store a Derived* in a std::vector<Base*> but not vice versa. Commented Jun 27, 2016 at 16:10
  • 2
    Think 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) Commented Jun 27, 2016 at 16:17

2 Answers 2

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*
Sign up to request clarification or add additional context in comments.

2 Comments

Will I be able to do it even if the derived class has additional public functions?
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.