Thursday, December 25, 2008

Overloading and Overriding are NOT the same

As the heading of this post clearly states, Overloading and Overriding have got not even a darn thing in common to be spoken together in any context. Beginners often tend to get confused between these two totally different terminologies, may be because they rhyme so well. Anyways, we will be discussing about these two jargons today.

Do you know what does a Function Signature consist of?

A function's signature consists of the number and type of its declared arguments (otherwise known as "formal" arguments). Consider the function definition,

void function1(int,int);

This statement says, function1 is a function taking two integer arguments and returning nothing (void return type).

Now that you are aware of function signatures, let’s move on with the Overloading concept…

Overloading occurs when two or more functions in the same scope have the same name and different signatures. When the compiler looks up a function name and finds more than one function with that name in a scope, it selects among the available candidates in that scope for the one whose formal arguments best match the actual arguments of the function call. This is what called as “Overloading”.

Overriding occurs in case of Polymorphism i.e, when a derived class function has the same name and signature as a base class virtual function. In such cases, whenever a virtual call to a derived object occurs, the implementation of the derived class function will replace that of the inherited base class function. Basically, Overriding changes the behavior of a class but not its interface.

Consider the following simple base class:
class base {
public:
//...
int fn( int );
void fn( float );
//...
};

In this example, the function fn is overloaded in the class base because two different functions named fn are with in the same scope.

To squeeze in the concept of Overriding, let’s consider the below code…


class base {
public:
//...
virtual int fn( int );
void fn( float );
//...
};

class derived : public base {
public:
int fn( int );
int fn( float );
};

The member function derived::fn(int) overrides the base class virtual function base::fn(int). The member function derived::fn(float) doesn't override anything, because base::fn(float) is not virtual. It does, however, overload derived::fn(int). Note that it does not overload the base class member base::fn, because it's in a different scope.

Variation:

Is it not necessary to use the keyword virtual in the derived class’ fn function?

The member function derived::fn(int) overrides the base class’ fn function and so it is defined virtual in the base class; the use of the keyword virtual in the derived class is completely optional and has no effect on the meaning of the program. A common misassumption is that omitting the virtual keyword in the derived class will prevent further overriding in more derived classes. This is not the case.

0 comments: