The expected output:
Child = 2
Parent = 1
My code:
class Parent{
int a;
public:
void display(){
a = 1;
cout << "Parent = " << a << endl;
}
};
class Child:public Parent{
int b;
public:
void display(){
b = 2;
cout << "Child = " << b << endl;
}
};
int main()
{
Parent *p = new Child();
Child c;
//write your code here
/* My solution :
c.display();
Parent* a = &c;
a->display();
*/
}
I made use of static binding to successfully call the display() member function of the parent class
However, I wonder if there is any better solution for this question.
What is the purpose of having this line Parent *p = new Child();
? Is it a pointer pointing to a constructor?
What is the difference between that line and Parent *p = new Child;
?