News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

Difference between Overloading and Overriding in C++

Started by thiruvasagamani, Jul 10, 2008, 07:10 PM

Previous topic - Next topic

thiruvasagamani

In C++, overriding is a concept used in inheritance which involves a base class implementation of a method. Then in a subclass, you would make another implementation of the method. This is overriding. Here is a simple example.

class Base
{
public:
virtual void DoSomething() {x = x + 5;}
private:
int x;
};
class Derived : public Base
{
public:
virtual void DoSomething() { y = y + 5; Base::DoSomething(); }
private:
int y;
};

Here you can see that the derived class overrides the base class method DoSomething to have its own implementation where it adds to its variable, and then invokes the parent version of the function by calling Base::DoSomething() so that the x variable gets incremented as well. The virtual keyword is used to that the class variable can figure out which version of the method to call at runtime.

Overloading is when you make multiple versions of a function. The compiler figures out which function to call by either

1) The different parameters the function takes
                  or
2) the return type of the function. If you use the same function declaration, then you will get a compiler error because it will not know which function to use. Here is another simple example.

class SomeClass
{
public:
void SomeFunction(int &x) { x *= x; }
int SomeFunction(int x) { return x * x; }
};

// In main()
SomeClass s;
int x = 5;
x = SomeFunction(x);

The compiler knows to call the second implementation of the method because we are assigning the return value from the function to x.
Thiruvasakamani Karnan


RADHA KRISHNA

Thanks for your answer by which i ve understood the concept easily

alenfort

The Difference between Overloading and Overriding in C++

- Overload - two functions have the same name and return
Type, but different types and / or the number of parameters.

- Overriding - When a function is to redefine the base class
Derived class.

Theodore

Hello guys....!
overloading is giving an operator meaning which is needed for us i mean the operator can do the job as we want if we overload but overriding is giving some diffrent meaning in to a function which specified in parent process in inheritance...!