Reputation: 21
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;
}
Upvotes: 2
Views: 129
Reputation: 117298
The non-const
display()
in Derive
is hiding the const
display()
in Base
.
Add this in Derive
to bring it in:
using Base::display;
Note that you now have two virtual
overloads that may be overridden separately.
class Last : public Derive {
public:
void display() override { std::cout << "non-const overridden\n"; }
void display() const override { std::cout << "const overridden\n"; }
};
int main() {
Derive* l1 = new Last;
l1->display(); // prints non-const overridden
const Derive* l2 = new Last; // prints const overridden
l2->display();
}
Upvotes: 2