Operator/ Function Overloading and Inheritance
There is some pre-defined set of rules on operator overloading:
- We can't overload below operators because they take a name, rather than a value as their second operand:
- scope resolution (::)
- member selection (.)
- member selection through pointer to member (.*)
- We can't overload below operators:
- typeid
- sizeof
- conditional ternary operator ( ? : )
- Below operators must be non-static functions and the reason is, these operators
requires their first operand as lvalues:
- operator=
- operator[],
- operator()
- operator-> Except for the assignment operator, all other operators are automatically inherited into a derived class.
Just like constructor and destructor, conversion operators won't have return type. Return type will be with the name of the function.
int iNum;
public:
operator int() {
return iNum;
}
};
Number n(7);
int num = n; //Calls conversion operator int.
Providing exact signature and return type for a base class function in derived class is called re-defining and if that base class function is virtual, then it's called as overriding. But changing argument list or return type in derived class leads to name hiding. Name hiding will cause in hiding all other base class's overloaded functions in derived class. Name hiding is achieved by changing either return type or parameter list. But, if the base class function is virtual, then we can't change the return type in derived class.
But there is a scenario, where we can change the return type of base class virtual function. If we are returning a pointer or reference to a base class in the base class virtual function, then the overridden version of the function may return a pointer or reference to a class derived from what the base's virtual function returns. This is valid because, in C++ upcasting is done defaultly (implicitly). In other case, we can't change the return type of virtual function because; we can't call that function with base pointer/reference.
Generally non-virtual base function won't be re-defined in derived class because, nonvirtual functions are dispatched based on the static type of the pointer/reference rather than dynamic type of the pointed-to/referenced object during runtime. So, if you re-define it in derived class, then all existing code may behave differently. Even though re-defining a non-virtual base function in derived class is not a good idea, it will be useful in some scenario where derived class function hides base class function and compiler does not support using keyword.
Example:
Public:
void Foo(int);
};
public:
void Foo(float );
//This hides Base::Foo(int) in derived
};
To have both Base and Derived versions of Foo, we have two different solutions as below:
public:
//use using to get Base::Foo
using Base::Foo;
void Foo(float );
};
public:
//re-define Foo(int) and call Base::Foo
void Foo(int i ) {
Base::Foo(i);
}
void Foo(float );
};






Operator/ Function Overloading and Inheritance