Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloaded functions are hidden in derived class

In a derived class If I redefine/overload a function name from a Base class,
then those overloaded functions are not accessable/visible to derived class.
Why is this??

If we don't overload the oveloaded function from the base class in derived class then all the overloaded versions of that function are available to derived class
objects, why is this??
what is the reason behind this. If you explain this in compiler and linker level
that will be more helpful to me. is it not possible to support this kind of scinario??

Edited  
For examble:

class B  
{  

  public: 
     int f() {}
     int f(string s) {}
};

class D : public B
{
   public:
    int f(int) {}
};

int main()
{
   D d;
   d.f(1);
   //d.f(string);  //hidden for D
} 

Now object 'd' can't access f() and f(string).
like image 332
esh Avatar asked Jul 08 '10 09:07

esh


People also ask

Can we overload derived class?

The reason is the same as explained in the case of the C++ program. In C#, just like in C++, there is no overload resolution between class Base and class Derived. Also, there is no overloading across scopes and derived class scopes are not an exception to this general rule.

Can derived class inherit overloaded operators?

All overloaded operators except assignment (operator=) are inherited by derived classes.

Can we overload a function of superclass in derived class?

You can override or overload a function in the derived class. If you have another function with the same name as the inherited function but different parameter lists it is called overloading functions. Both of these can exist.

What are the restrictions on overloaded function?

Restrictions on overloadingAny two functions in a set of overloaded functions must have different argument lists. Overloading functions that have argument lists of the same types, based on return type alone, is an error.


1 Answers

TTBOMK this doesn't have a real technical reason, it's just that Stroustrup, when creating the language, considered this to be the better default. (In this it's similar to the rule that rvalues do not implicitly bind to non-const references.)

You can easily work around it be explicitly bringing base class versions into the derived class' scope:

class base {
public:
  void f(int);
  void g(int);
};

class derived : public base {
public:
  using base::f;
  void f(float);
  void g(float); // hides base::g
};

or by calling the explicitly:

derived d;
d.base::g(42); // explicitly call base class version
like image 112
sbi Avatar answered Oct 13 '22 10:10

sbi