Reputation: 313
I am just trying to understand this piece of code below but could not understand these 2 lines at the end.
ptr = &D;
ptr->show();
I am actually on my way to study polymorphism concept. And this is just basics of that. So please explain me how it is working and why ptr->show() is calling function in base.
#include <iostream>
using namespace std;
class Base {
public:
void show()
{
cout << "This is the base\n";
}
};
class Derived : public Base {
public:
void show()
{
cout << "This is the derived\n";
}
};
int main()
{
Base B;
B.show();
Derived D;
D.show();
Base *ptr = &B;
ptr->show();
ptr = &D;
ptr->show();
return 0;
}
Output
This is the base
This is the derived
This is the base
This is the base
Upvotes: 0
Views: 53
Reputation: 23565
Base is a simple class.
Derived is a class that inherit from Base. (We will say that Derived is the daughter of Base, and Base is the mother of Derived)
Let's see the effects of inheritences :
B is an instance from Base
Base B;
Call method show of class Base
B.show();
D is an instance from Derived
Derived D;
Call method show of class Derived
D.show();
Create a pointer to Base class intialized to the address of B object (Base class)
Base *ptr = &B;
Call method show of Class Base, cause ptr is a Base pointer
ptr->show();
Initialise ptr pointer with the address of D object (Derived class)
ptr = &D;
Call method show of Class Base, cause ptr is a Base pointer
ptr->show();
Why is it working like that? Why does he did not call Derived show method?
Imagine compilator algorithm...
You told to him : "Please call the methods show! For class pointed by ptr"
So it look after the type of value pointed by ptr (Class Base) and look after the method show. Does the function show have the keyword virtual?
No? So i call it now!
Yes? So i am going throught all daughter and take the last definition of show and then call it!
Do you get it?
If you have any question you are wwelcome buddy!
Upvotes: 0
Reputation: 311088
Member functions are called accordingly to the static type of the pointer. If you would define function show as virtual in this case it were called when ptr assigned by address of the derived class due to indirect call using vptr.
As you declared ptr as Base *ptr
that is its static type is Base then the compiler call member function show defined in class Base
.
Upvotes: 1