There was this question in my quiz. Can you explain it?
Pointer to a base class can be initialized with the address of derived class, because of ______.
The correct answer was 'derived-to-base implicit conversion for pointers'.
I have some questions related to this code:
#include <iostream>
using namespace std;
class Base
{
protected:
int x;
public:
Base(){};
Base(int x1): x(x1) {};
void show()
{
cout<<"x = "<<x<<endl;
}
virtual void printData()
{
cout<<"x = "<<x<<endl;
}
};
class Derived: public Base
{
int y;
public:
Derived(){};
Derived(int x1, int y1): Base(x1), y(y1) {};
void showXY()
{
cout<<"x = "<<x<<endl;
cout<<"y = "<<y<<endl;
}
void printData()
{
cout<<"x = "<<x<<endl;
cout<<"y = "<<y<<endl;
}
};
int main()
{
Base *d1 = new Derived(1,2);
// d1->showXY(); gives error in running a derived class function
d1->show(); // runs a base class function
d1-> printData(); // runs a virtual (overriden) derived class function
d1->~Base(); // uses a base class destructor
}
Please explain this concept. Is it a base class object or a derived class object? because it runs base class functions but if there is overriding then it runs derived class function but gives error on running pure derived class functions.