Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloading and overriding

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);
}
like image 321
Rabea Shamaly Avatar asked Jul 30 '17 16:07

Rabea Shamaly


2 Answers

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.

like image 128
AndyG Avatar answered Oct 23 '22 04:10

AndyG


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);
  // ^^^
like image 1
user0042 Avatar answered Oct 23 '22 02:10

user0042