The code looks like this.
Why p1->display() causes a build error?
How can I call display() const by a Derived ptr?
#include <iostream>
using namespace std;
class Base
{
public:
virtual void display() const
{
std::cout << "Base display const!" << std::endl;
}
virtual ~Base(){}
};
class Derive: public Base
{
public:
virtual void display()
{
std::cout << "Derive display!"<< std::endl;
}
virtual ~Derive(){}
};
int main()
{
const Base *pb1 = new Derive();
pb1->display(); // Base display const!
Base *pb2 = new Derive();
pb2->display(); // Base display const!
const Derive *p1 = new Derive();
//p1->display(); // Build Error
Derive *p2 = new Derive();
p2->display(); // Derive display!
return 0;
}