I have a very basic question concerning inheritance in C++:
class A
{
public:
void foo() { print(); }
protected:
void print() {}
};
class B : public A
{
protected:
void print() { std::cout << "test" << std:: endl; }
};
Now the following code
B b;
b.foo();
doesn’t print anything, so foo() obviously didn’t call the newly defined print(). Is this only solvable by using virtual methods?
Yes, you need to make
printvirtual in order for this to work. Otherwise,A::foohas no idea that descendants could provide alternative implementations ofprint, an happily callsA‘s version. Compiler may even inline theprintinsidefooat the timeA‘s code is compiled, making the implementation inBcompletely irrelevant.