An Example/Tutorial of the Virtual Keyword.
The Virtual Keyword in C++ is used for inheritance and is an important concept in Object Orientated Programming and the Polymorphism buzzword. The Virtual Keyword in a base class indicates a method can be used by a derived class or be defined or overridden with its own function.
The term “Pure Virtual” comes from when you declare a method in a class as such: virtual void MyFunction() = 0;
By appending the “= 0″ part this means the virtual member function has no implementation. This creates an abstract method by which makes the Class an Abstract Class.
An Abstract Class cannot create an instance of itself, only a pointer to itself can apply, however derived classes of the Abstract Class can.
The computer knows which virtual function to call from base and derived classes from the compiler setting up a virtual table, like the symbol table, the virtual table has pointers to each of the virtual functions and classes. The compiler sets up a hidden pointer *__vptr automatically for each class instance so that it points to the virtual table for that class. It is different from the *this pointer which is actually a function parameter for self references. the vptr is a real pointer and makes the classes bigger by one pointer. vptr is also inherited by derived classes
The diamond problem, also comes up with multiple inheritance. This is where if you have base class A, and derived class B and C, and class D derives from B and C, the compiler will find it ambiguous and does not know which path of derivation to take for class D, does class D derive A from class B or does class D derive from class C from A? To solve this problem the virtual keyword can also be used here, by creating each derived class B and C like this:
class B : virtual public A
class C : virtual public A
The virtual keyword here will virtually inherit from A, thus solving the ambiguity of class D.
C++ Virtual Keyword Example
Popularity: 14% [?]