Just in case you still hadn't fully comprehended the concept behind inheritance and polymorphism, I'll leave you few notes here.
Q.When we inherit the features of a derived class, does this mean that we also have inherited the features which the derived class already inherited from? |
In short, yes.
The long version: (note: try to visualize it on paint if you get confused)
Think of inheritance as copying the contents of one class into another. So suppose you have three classes A, B and C. Suppose that B inherits from A; therefore B is a derived class and A is a base class. Now suppose that C inherits from B. Since B inherits from A, this means all the methods inside of the class A are copied into the class B (granted that the methods of class A are made public). So since C inherits from B, this means all the methods of B (including those already inherited from other classes) are also copied in class C.
Q.What exactly is the use of the virtual keyword? Do we only use it whenever we expect to override a certain function in a derived class? |
In short, you use the virtual keyword in a base class whenever you want to give a specific function multiple definitions in different derived classes.
The long version: (note: try to visualize it on paint if you get confused)
When you create a function as virtual, 2 things gets created behind the scene. A virtual pointer, and a virtual table. The virtual pointer will point to the virtual table and store its address. The virtual table can be thought of as an array of pointers to virtual functions, each pointer will store the memory address of a virtual function you have in a class. When you inherit from this base class, the virtual pointer (short for vptr) and virtual table (short for vtable) also get inherited. So you can imagine how costly it can be if you have plenty of virtual functions. When you override a virtual function in your derived class, a pointer in the virtual table will start pointing to it and keep track of it.
Note: A good rule of thumb is to make the destructor virtual whenever you have a virtual function to ensure that a derived object have a chance to clean up after itself. Also, another good rule of thumb is to always put the keyword virtual next to your virtual functions in the derived class (although not necessary because when they are virtual in the base class, they are virtual everywhere) as they can still serve as a reminder that this particular function is virtual.
Hope this helps.