Main menu

C++: Why virtual? (Part-1)

C++ is a Object Oriented language. C++ uses virtial keyword for different places. One of this is in creating virtual functions.

One of the Object Oriented feature is Polymorpishm which means multiple-behaviours. An object has multiple behaviours and it shows particular behaviour depending on its context. C++ achieves this with the help of virtual keyword by defining virtual functions.

Lets take a simple example.

Create a class Shape and add one public method Display. Display just displays the name of the class.

Derive a class Circle from Shape class and add a method Display.

Now create an instance of Circle class and assign it to a variable of type Shape.

After running this, it will display “Shape” instead of “Circle”. Actually in main(), we have created Circle class’s instance; but assigned to Shape type variable. We expect the result “Circle”. But it calls Shape‘s Display method instead of Circle‘s Display method. This is the place we need virtual keyword.

By adding virtual keyword to Display method, at runtime it will call the exact method irrespective of the type of the object through which we are calling the method. In this case, it calls, Circle‘s Display method instead of Shape‘s Display method; which is what we are expecting.

We will discuss about other places where C++ using virtual keyword, in our next article.

Featured Posts

As of now, we have created our window and successfully displayed on the screen. We have seen this in our previous article. And also we observed that the window is immediately closed; because of no user interaction code was added.…