1

I am new to Inheritance..

#include<iostream>
using namespace std;
class base
{ public:
    void show()
     {
       //do something here
         }  
    };

class derive:public base
{ public:
 void show(int n,int m)
    { 
      //do something
        }};


int main()
{
derive D;
  D.show();
  D.show(4,5);
    }

So the compiler is giving error that: no matching function for call to ‘derive::show()

  • 2
    Please indent your code in one of the normal styles. This style is exceedingly difficult to read. – Justin Mar 10 '18 at 05:44
  • Just edited, to the simplest form. –  Mar 10 '18 at 05:49
  • Possible duplicate of [Function with same name but different signature in derived class](https://stackoverflow.com/questions/411103/function-with-same-name-but-different-signature-in-derived-class) – Silvio Mayolo Mar 10 '18 at 05:54

2 Answers2

1

When the compiler processes

D.show();

it first checks whether the name show is present in derive. If it is, it does not look in the base class for the name. After that, it tries to find the best match for it. In this case, there is no match since the only function named show in derive expects two arguments of type int. Hence,

D.show();

is not valid.

If you want base::show to be available as an overload in derive, you have to let the compiler know.

class derive : public base
{
   public:

      // Let the functions named show from base be available
      // as function overloads.
      using base::show;

      void show(int n,int m)
      {
         cout<<"Derive Version.."<<n<<","<<m<<endl;
      }
};

Now, you can use:

int main()
{
   derive D;
   D.show();
   D.show(4,5);
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

The compiler is correct. In the derive class there is no functionshow(). What I am guessing you want is to access the base class function however. To do this, you have to specify that it is the base class, not the derived class. To do this all you need to do is scope to the base class doing something like the following:

derive D;
D.base::show();       //Uses the bases function

D.derive::show(4,5);  // Uses the derived function
D.show(4,5);          // Uses the derived function
Hawkeye5450
  • 672
  • 6
  • 18
  • 1
    I always wondered if this resulting (necessary) syntax can be used for a good purpose if the classes are named nicely if it has template parameters. Like `D.fancy<5>::call()`. – alfC Mar 10 '18 at 05:57