C++ Operator overloading Interview Questions and Answers
What is operator overloading in C++?
C++ provides ability to overload most operators so that they perform special operations relative to classes. For example, a class String can overload the + operator to concatenate two strings.
When an operator is overloaded, none of its original meanings are lost. Instead, the type of objects it can be applied to is expanded. By overloading the operators, we can use objects of classes in expressions in just the same way we use C++’s built-in data types.
Operators are overloaded by creating operator functions. An operator function defines the operations that the overloaded operator will perform on the objects of the class. An operator function is created using the keyword operator.
Explain function overloading?
Function overloading is the process of using the same name for two or more functions. The secret to overloading is that each redefinition of the function must use either different types of parameters or a different number of parameters. It is only through these differences that the compiler knows which function to call in any situation.
What is overloading unary operator?
Unary operators are those which operate on a single variable. Overloading unary operator means extending the operator’s original functionality to operate upon object of the class. The declaration of a overloaded unary operator function precedes the word operator.
What is overloading template?
A template function overloads itself as needed. But we can explicitly overload it too. Overloading a function template means having different sets of function templates which differ in their parameter list. Consider following example:
template void func(X a)
// Function code;
cout <<”Inside f(X a) \n”;
template void func(X a, Y b) //overloading function template func()
// Function code;
cout <<”Inside f(X a, Y b) \n”;
func(10); // calls func(X a)
func(10, 20); // calls func(X a, Y b)
Difference between overloaded functions and overridden functions.
Overloading is a static or compile-time binding and Overriding is dynamic or run-time binding.
Redefining a function in a derived class is called function overriding
A derived class can override a base-class member function by supplying a new version of that function with the same signature (if the signature were different, this would be function overloading rather than function overriding).