This code generates the following compilation error :
error: no matching function for call to 'C::print(int)'
can you help me figuring out the procedure that the compiler did to generate that error , (why it ignored the function in class B)
#include <iostream>
using std::cout;
class A {
public:
  virtual void print () 
   { cout << "A";}
};
class B : public A {
   int x;
 virtual void print (int y) 
   {cout << x+y;}
};
class C : public B {
public:
  void print ()
   {cout << "C";}
};
int main () {
  C* ptr = new C;
  ptr->print (5);
}
                Each subsequent definition of print hides its parent's. You need a using statement to unhide it:
class A {
public:
  virtual void print () 
   { cout << "A";}
};
class B : public A {
public:
   int x=1;
 using A::print;
 virtual void print (int y) 
   {cout << x+y;}
};
class C : public B {
public:
  using B::print;
  void print ()
   {cout << "C";}
};
Your pointer is to C*, not B*. You wouldn't technically need to 'unhide' any print functions if your code looked like this:
B* ptr = new C;
However that this sort of hiding is not a particularly good idea... you should prefer overriding and just naming functions different things.
The compiler resolves overloads for the closest (class) type seen. So class C effectively hides the function signature inherited from class B.
To call for that specific function you have to qualify its scope explicitely:
ptr->B::print (5);
  // ^^^
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With