What are virtual classes?

Showing Answers 1 - 1 of 1 Answers

samiksc

  • Jan 20th, 2006
 

Virtual base class is a term used in C++ multiple inheritance.

Assume the following -- base class P. Two classes A and B derive from P. A third class C derives from both A and B.

P has a protected variable pvar. A class C method accesses this variable. Now there are two copies of pvar available for C to use -- A::pvar and B::pvar. So the compiler gives error for ambiguity.

If, however, classes A and B declare P as virtual base class this problem would be avoided. When a base class is declared as virtual only one copy of its data members exist in memory. At runtime it will be checked whether an object of the base class P is created in memory, if not it will be created, if yes the same copy will be referred. So there will be no ambiguity.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions