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.
}
Aucun commentaire:
Enregistrer un commentaire