Monday, June 23, 2008

What is overriding in C++?

  • Redefining a base class function in the derived class to have our own implementation is referred as overriding.
  • Often confused with overloading which refers to using the same function name but with a different signature. However in overriding the function signature is the same.

Demonstrate the usage of overriding

#include <iostream>
using namespace std;

class Base {
    public:
        virtual void myfunc() {
            cout << "Base::myfunc .." << endl;
        }
};

class Derived : public Base {
    public:
        void myfunc() {
            cout << "Derived::myfunc .." << endl;
        }
};

void main()
{
    Derived d;
    d.myfunc();
}
OUTPUT:-
Derived::myfunc ..

8 comments :

  1. I think no need to declare function virtual here.

    ReplyDelete
  2. Yes you are correct there is no need for virtual keyword here but this concept(overriding) is used when we access some function or data through base class pointer and want to have desired output as above.

    in that case main will change code as shown below
    void main()
    {
    Derived d;
    Base *b = &d;
    b->myfunc();
    }

    ReplyDelete
  3. Thank you. IT is very easy to understand.

    ReplyDelete
  4. i don't understand !!
    if what you meant is what understood that means that overriding is what we usually do in the code !!

    ReplyDelete
  5. bcoz the object is of derived class so everytime when u will call function
    "myfunc" the derived class myfunc will run. thats what you want to show in this example????

    ReplyDelete
  6. ok is it mean when we use pointer with class and use this sign(->)
    so its overriding ?!?

    ReplyDelete
  7. how can we call the myfun() defined in the base class?

    ReplyDelete
  8. just remove Virtual keyword from myfun() in base class..
    then following code call the base class myfun()
    void main()
    {
    Derived d;
    Base *b = &d;
    b->myfunc();
    }

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top