Reputation: 45
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.
Upvotes: 0
Views: 911
Reputation: 81
You created a Base class pointer *d1 which is pointing to the derived class object because new keyword allocated the memory address of derived class object dynamically to Base class pointer *d1.
Base *d1 = new Derived(1,2);
now when you call member functions of a class using a pointer so it calls it using Early binding. So for every function call base class member functions are going to be called. But the virtual function printData() will be called using Late Binding and derived class's overriden printData() will be called.
Now for the destructor call, @eerorika stated right.
Upvotes: 1
Reputation: 238351
Is it a base class object or a derived class object
A derived class object was created dynamically. That is the dynamic type of the object. The derived object contains a base sub object. d1
points to the base sub object. That is the static type of the pointer.
d1->~Base();
This is bad for two reasons:
delete
should be used (if the destructor was virtual).Upvotes: 1