Module 2
Module 2
■ A virtual function is a member function that is declared within a base class and
redefined by a derived class.
■ To create virtual function, precede the function’s declaration in the base class with the
keyword virtual.
■ When a class containing virtual function is inherited, the derived class redefines the
virtual function to suit its own needs.
■ Base class pointer can point to derived class object. In this case, using base class pointer
if we call some function which is in both classes, then base class function is invoked.
But if we want to invoke derived class function using base class pointer, it can be
achieved by defining the function as virtual in base class, this is how virtual functions
support runtime polymorphism.
Class A Class B: public A
{ { int main()
int a;
int b; {
public:
A() public: A *pA;
{ B() B oB;
a = 1; { pA = &oB;
} b = 2; pA→show();
virtual void show() } return 0;
{ virtual void show() }
cout <<a;
}
{
}; cout <<b;
}
};
■ Pure virtual Functions are virtual functions with no definition. They start with virtual
keyword and ends with = 0. Here is the syntax for a pure virtual function,
virtual void f() = 0;
■ Pure Virtual functions can be given a small definition in the Abstract class
■ Pure Virtual function must be defined outside the class definition. If you will define it
inside the class definition, complier will give an error. Inline pure virtual definition is
Illegal.
What is a virtual base class?
■ An ambiguity can arise when several paths exist to a class from the same base class.
This means that a child class could have duplicate sets of members inherited from a
single base class.
- C++ solves this issue by introducing a virtual base class. When a class is made virtual,
necessary care is taken so that the duplication is avoided regardless of the number of
paths that exist to the child class.
■ When two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those objects
by declaring the base class as virtual when it is being inherited. Such a base class is
known as virtual base class. This can be achieved by preceding the base class’ name
with the word virtual.