6

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);
}

3 Answers3

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";}
};

Demo

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.

AndyG
  • 39,700
  • 8
  • 109
  • 143
1

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);
  // ^^^
user0042
  • 7,917
  • 3
  • 24
  • 39
0

overloading means two things(eg functions) have same name in same space or scope like in same class but in overriding we rewrite the definition of function in different scope(class) but the name still remains same.