0

How can I point pointer array of class A at index 1 to a derived class object. so when I write pointer[1].print(), it calls the print function from class B. (its index 0 should remain pointing the the object of type A)

#include <iostream>
using namespace std;
class A
{
protected:
string name;
public:
A()
{
name="A";
}
virtual void print()
{
cout<< name;
}
};


class B : public A
{

public:
B()
{
name="B";
}
void print()
{
cout<< name;
}
};

int main()
{
A *pointer=new A [2];
pointer[0].print(); //prints A

//now I want index 1 to be pointed to object of child class B
//so when I write pointer[1].print()
// "B" is printed. 
}

1 Answers1

3

A* pointer = new A[2]; reserves space for exactly two As. You simply cannot force a B into this location because (usually) it requires more space.

Polymorphism generally only works via pointers or references:

void demo1(A a);  // accept a by value; you *can* pass a B to, but then only its
                  // A part is copied, anything belonging to B gets lost
                  // this is called object slicing
void demo2(A& a); // now can accept both A and B without losing any
                  // type information
void demo3(A* a); // alike...

Same applies for arrays, solely the reference option is not available:

A** array = new A*[2] { new A(); new B(); };

If you allocate via new, don't forget to delete them as well to avoid memory leaks.

You might want to prefer smart pointers to avoid explicit memory management for the created objects; a std::vector of smart pointers relieves you from any memory management entirely (in above example you need to delete[] array manually as well):

    std::vector<std::unique_ptr<A>> v;
    v.reserve(2);
    v.push_back(std::make_unique<A>());
    v.push_back(std::make_unique<B>());

Unfortunately, std::initializer_list constructor is not usable as std::unique_ptr is not copiable.

Other ways to initialise the vector are demonstrated here, but these aren't necessarily better either.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59