Inheritance Part 3, Virtual Base Class
Virtual Base
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 proceeding the base class name with virtual.
Ex:
class
a
{
---
---
};
class
b: virtual public a
{
----
----
};
class
c:virtual public a
{
----
----
};
class
d:public b,public c
{
----
----
};
In this example, classes B
and C inherit features from class A.
Derived class D inherits
features from classes B and C.
Derived class D inherits
features of class A twice through classes B and C
To solve this problem derived
class B and C should be declared as virtual.
Abstract classes:
An abstract class is one
that is not used to create objects
This class is designed
only to act as a base class.
Constructors and destructors in Inheritance:
When both derived class
and base class contains constructors, the base class constructor is executed
first and then constructer in the derived class is executed.
When both derived class
and base class contains destructor, the derived class destructor is executed
first, and then destructor of base class is executed.
Comments
Post a Comment