2

Consider the below simple example:

class base{
public:
void func(){
    cout<<"Base class no arg"<<;
}
};

class derived: public base{
public:
void func(int x){
    cout<<"Derived class 1 arg"<<endl;
}
};

When I make an object of derived class and call the function func without any parameter, should it not call the func defined in base class?

derived d1;
d1.func();

I get the following error:

error: no matching function for call to 'derived::func()'

Can anyone please explain why this behavior exists?

  • Your `#func()` is not virtual, so (I believe) it will check against the explicit type of `d1` (derived), and see no `#func()` defined. Note your signatures mismatch: `base#func()` != `derived#func(int)`, so if you were aiming to make them virtual, you'd still have that issue to contend with (they're essentially separate functions). – Rogue Nov 15 '22 at 16:09
  • A derived class that *shadows* a function from the base class **hides** that base class function. You can do a `using` to expose the base class function in the derived class, or write a *thunk* routine in the derived class that calls the base class function. (I think most folks would do the `using`, I prefer doing the *thunk*.) – Eljay Nov 15 '22 at 16:16
  • 1
    Overloading applies to names that are defined in the same scope. Those two versions of `func` are not defined in the same scope, so there is no overloading. – Pete Becker Nov 15 '22 at 17:14

0 Answers0