Sie sind auf Seite 1von 2

Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a

given class appearing in an inheritance hierarchy when using multiple inheritance.

Consider the following scenario:

class A { public: void Foo() {} }

class B : public A {}

class C : public A {}

class D : public B, public C {}

The above class hierarchy results in the "dreaded diamond" which looks like this:

/\

B C

\/

An instance of D will be made up of B, which includes A, and C which also includes A. So you
have two "instances" (for want of a better expression) of A.

When you have this scenario, you have the possibility of ambiguity. What happens when you do
this:

D d;

d.Foo(); // is this B's Foo() or C's Foo() ??

Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your
classes, you're telling the compiler that you only want a single instance.

class A { public: void Foo() {} }

class B : public virtual A {}

class C : public virtual A {}

class D : public B, public C {}

This means that there is only one "instance" of A included in the hierarchy. Hence

D d;
d.Foo(); // no longer ambiguous

Hope that helps as a mini summary. For more information, have a read of this and this.

Cheers!

Polymorphic means many forms. The object of the polymorphic class pointer can store any
derived class objects and called respective member functions when its object member
functions is called automatically instead of calling base class member function.

By using "Virtual" key word in front of Base class member function, the base class become
polymorphic class. when this member function assigns = 0 then it becomes pure virtual
function and Base class become Abstract class.

The advantage of polymorphic class are

1. Late binding (run time)


2. It acts as interface between implementation and calling class.
3. The polymorphic class pointer can be assigned with array of derived class objects and called
respective member functions.
4. Encapsulation can be achieved in the form of API (actual implementation).

Das könnte Ihnen auch gefallen