Reputation: 309
Recently, I am learning the Inheritance. Here is my code.
#include <iostream>
using namespace std;
class Pad{
public:
void Show(){
cout<<"this is pad ";
}
};
class Decorator: public Pad{
protected:
Pad* mpad;
public:
Decorator(Pad* ipad){
mpad = ipad;
}
void Show(){
mpad->Show();
}
};
class CoverDecorator: public Decorator{
protected:
public:
CoverDecorator(Pad* ipad):Decorator(ipad){
}
void Show(){
mpad->Show();
cout<<"with Cover";
}
};
int main()
{
Pad* ipad = new Pad;
Pad* Coverpad = new CoverDecorator(ipad);
Coverpad->Show();
return 0;
}
But I found that it printed out "this is pad" instead of "this is pad with Cover" .
It means that in Coverpad->Show()
, it implements the function void Show()
of class Pad instead of implementing the void Show()
of class CoverDecorator.
Why and How do I make it implement the void Show()
of class CoverDecorator ?
Thanks!
Upvotes: 0
Views: 76
Reputation: 5637
All you need to do is make the base function virtual
:
class Pad{
public:
virtual void Show(){
cout<<"this is pad ";
}
};
It is also important to note that when creating a virtual function, although the it is not needed, it is good practice to label the derived functions with the override
keyword:
class Decorator: public Pad{
protected:
Pad* mpad;
public:
Decorator(Pad* ipad){
mpad = ipad;
}
void Show() override {
mpad->Show();
}
};
Declaring a function as virtual
basically means that that function will not bind statically at compile time, and instead bind dynamically during the runtime of the program (this allows polymorphism).
Upvotes: 1
Reputation: 6360
With C++ inheritance, declaring certain methods within the base and derived classes as virtual
means they are subject to change within the derived classes and will be called as such.
virtual <return type> <name>(){}
Upvotes: 0