Wednesday, March 28, 2018

Write a case study on using virtual classes (150 Words)


AIM: Write a case study on using virtual classes (150 Words)
THEORY:
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.
Suppose you have two derived classes B and C that have a common base class A, and you also have another class D that inherits from Band C. You can declare the base class A as virtual to ensure that B and C share the same subobject of A.
In the following example, an object of class D has two distinct subobjects of class L, one through class B1 and another through class B2. You can use the keyword virtual in front of the base class specifiers in the base lists of classes B1 and B2 to indicate that only one subobject of type L, shared by class B1 and class B2, exists.
For example:

class L { /* ... */ }; // indirect base class
class B1 : virtual public L { /* ... */ };
class B2 : virtual public L { /* ... */ };
class D : public B1, public B2 { /* ... */ }; // validcopy to clipboard
Using the keyword virtual in this example ensures that an object of class D inherits only one subobject of class L.


Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home