SHOW / EPISODE

EP 3 - [C++] Polymorphism, Function overriding and Virtual function.

Season 1 | Episode 3
8m | Jun 21, 2021

šŸš„ polymorphism is the occurrence of two or more different morphs or forms.šŸš„


In this episode, I am talking about Polymorphism and more specifically Runtime polymorphism. This episode is arranged in such a way that it will help you to understand the concept clearly. There are a few common interview questions and I am explaining the answer in the best possible way.


You can read the transcript below.


This is very important and frequently asked interview questions.

Ā 

Don't forget to subscribe to the podcast to get a notification.

You can listen on

āž”ļøĀ Amazon Music (https://music.amazon.com/podcasts/c5ed5ab6-e4e8-4932-a397-b687c85465da/PROGRAMMING-GYAN)

āž”ļøĀ Spotify (Programming Gyan)

āž”ļøĀ Apple Podcast (https://podcasts.apple.com/us/podcast/programming-gyan/id1568920481)

āž”ļøĀ Stitcher (https://www.stitcher.com/podcast/programminggyan)

āž”ļøĀ Google Podcast (https://podcasts.google.com/feed/aHR0cHM6Ly9mZWVkcy5yZWRjaXJjbGUuY29tL2JiOWQxMjEzLTFjODctNGRmZS1hNjZhLTIyM2MxNTc5NTE2OQ)

You have lots of options. So there is no reason not to listen.

Ā 

You can followĀ #programminggyan

LinkedIn:Ā ProgrammingGyan (https://www.linkedin.com/company/programminggyan)

Twitter: @GyanProgramming (https://twitter.com/GyanProgramming)

Instagram: @programming_gyan (https://www.instagram.com/programming_gyan)

Facebook: @ProgrammingGyan (https://www.facebook.com/ProgrammingGyan)

Ā 

To know more about me and to read blogs visitĀ www.jhadheeraj.com

Follow me at

#LinkedIn: @jhadheerajĀ (https://www.linkedin.com/in/jhadheeraj)

#Twitter: @dheerajjha_03 (https://twitter.com/dheerajjha_03)

#Instagram: @jha.dheeraj03 (https://www.instagram.com/jha.dheeraj03/


-------------------------------------------------------------------------------------------

Transcript:


Welcome to Programming Gyan [C++]- Tips and Tricks with Dheeraj Jha

EP 3 - Polymorphism, Function overriding, and Virtual function.

Ā Ā 

C++ is an object-oriented programming language. It supports all the OOP concepts. Today I am going to talk about one of the OOP concepts. Polymorphism.

Ā 

In biology, polymorphism is the occurrence of two or more different morphs or forms. It is the same in C++.

Ā 

Polymorphism in programming means the same name with a different implementation. This allows us to do an operation in many ways based on the input.

Ā 

In C++, you have two types of polymorphism: Overloading and Overriding.

Ā 

In this episode, I will talk about Overriding. And will talk about Overloading in another episode. It is important to know the use case where you can use the tool. The problem why we need a tool. I will talk in a format so that you will get to know all the things in sequence. This episode will also help you to prepare for common interview questions.

Ā Ā 

  • What is function overriding?

Inheritance allows us to create derived classes from the base class and inherit features of the base class. When we create a derived class object and call a function defined in the base class, the base class function gets called. If we redefine this function of the base class in the derived class, we can call the derived class function using the derived class object.

So what actually happened here is called Function Overriding.

Ā 

Code ref: https://godbolt.org/z/f4Wfbqcxn

Ā 

Remember here, function overriding is only possible when there is inheritance.

Ā 

  • Why we need a virtual function?
  • In what scenario we use the virtual function?

Now when we are talking about function overriding, it is important to talk about Virtual functions. So before we go deep into internals, let's understand why we need this? In which scenarios we can use this feature of C++?

Ā 

Consider you are developing an automotive application which deals with different types of vehicles. So you created a base vehicle class and derived different derived classes like a car, bike, etc. For simplicity, I will use the car and bike-derived classes.

Ā 

All the vehicles have some common high-level features like start, stop, accelerate, etc. So you added these functions in the base class and overridden them in derived classes. And you started using your derived classes with their own implementation. Everything is going well so far.

Ā 

You were enjoying your code and someday, you got a new requirement that the user will decide which vehicle he is using and your application should work as per the user's vehicle.

Ā 

Ohā€¦

Ā 

Now you donā€™t know which vehicle the user owns when you are writing your code. The type of vehicle will be decided at runtime when a user is using the application.

Ā 

To solve this you can check the type of vehicle user is providing at run time and call the appropriate function for the vehicle type. But this is not a good solution as your application may support more types of vehicles in the future.

Ā 

Here comes the virtual function for rescue.

Ā 

Code to refer: https://godbolt.org/z/ebc1Pn5eP

Ā 

  • How virtual function works?

Ā 

In the base class, you write a Virtual keyword before the function declaration to create a virtual function. When you create a virtual function in your class. There are a few things compiler does for you.

  • The compiler will add VTable for the class which has a virtual function.
  • Vtable is used by the compiler to keep track of virtual functions associated with the class.
  • There is only one instance ofĀ Vtable for each class and all the instances or objects of the class will point to this vtable.
  • Your C++ compiler adds function pointers in Vtable which will point to the virtual function which needs to be called. In short, Vtable stores function pointers of virtual functions.
  • When you instantiate an object of this class, the compiler will also add a pointer to the object. This pointer is usually referred to as vptr. When you instantiate an object, in the constructor this vptr pointer is initialized and it points to Vtable. All these things happen implicitly for you. So you need not write any extra code for this.
  • Remember a point here, if your class has a pure virtual function, there will be no entry in Vtable for pure virtual function as the pure virtual function doesn't have a definition. Although you can provide a definition of pure virtual function which I will discuss in a future episode.

Ā 

Before I move ahead, I want to mention here that the C++ standards do not mandate exactly how dynamic dispatch must be implemented. Compilers generally use minor variations on the same basic model.

Ā 

Now when you derive a class from the base class with virtual function,

a new Vtable is created for the derived class

  • It maintains the offsets ofĀ base class vtable
  • If you have any overridden virtual function in the derived class, the entry in vtable will be replaced by a derived class function definition.
  • If any base class virtual function is not overridden, its entry will be preserved.

Ā 

I hope you are clear now what happens when you create a virtual function in a class.

Ā 

Now let's consider the problem scenario I explained before.

Ā 

You will create a base vehicle class pointer that can point to any of the derived class objects.

Ā 

Vehicle *vehicleptr = nullptr;

Ā 

Now you can pass any object of the derived class and assign it to this vehicle pointer.

Ā 

You can now call vehicleptr->start(), vehicleptr->accelerate(), vehicleptr->stop().

Ā 

When you call any virtual function using a base class pointer, it checks in the vtable of the object, vehicleptr is pointing to. Calls respective function definition from the vtable and execute.

Ā 

I hope you can visualize here that now you don't have to worry about the user input. Whatever vehicle type object, the user is passing, your code will work as per that.

Ā 

I will add all the reference code links in the description, do check out those.

Ā 

There are few interview questions on this topic which I will discuss in a future episode.

Ā 

I hope, you got something new from this episode. Subscribe to this podcast and follow me on LinkedIn, Twitter, and Instagram. I will add links in the description. To know more about me you can visit www.jhadheeraj.com

Ā 

I will meet you in the next episode with some other interesting tips and tricks.

Ā 

Thank you for listening ProgrammingGyan [C++] -Tips and Tricks with Dheeraj Jha.

Audio Player Image
Programmin Gyan
Loading...