Virtual Function or Method in C++

Hi,

As an object-oriented programming language, C++ enables polymorphism. How can we do that? Well, we basically, we need to define a virtual function name (without implementation) within a base class, in which a derived class will actually implements the virtual function name. The derived class, will give us meaning to that defined virtual function within the base class.

Here is a simple, but a good example about the use of the keyword virtual in C++: (originally posted here)

Without “virtual” you get “early binding”. Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through.

With “virtual” you get “late binding”. Which implementation of the method is used gets decided at run time based on the type of the pointed-to object – what it was originally constructed as. This is not necessarily what you’d think based on the type of the pointer that points to that object.

class Base
{
  public:
            void Method1 ()  {  std::cout << "Base::Method1" << std::endl;  }
    virtual void Method2 ()  {  std::cout << "Base::Method2" << std::endl;  }
};

class Derived : public Base
{
  public:
    void Method1 ()  {  std::cout << "Derived::Method1" << std::endl;  }
    void Method2 ()  {  std::cout << "Derived::Method2" << std::endl;  }
};

/* Note - constructed as Derived, but pointer stored as Base*  */
Base* obj = new Derived ();

obj->Method1 ();  //  Prints "Base::Method1"
obj->Method2 ();  //  Prints "Derived::Method2"

That’s all,

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s