Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi everybody.
Say I have a class A which has a virtual (not abstract) function f. Now, this class is inherited by class B which overrides f.
What's exactly the difference between the two following class declarations:class B : public A
class B : public virtual AThanks in advance,
Itai.

Simply put: in the above case nothing.
Consider virtual inheritance as a way of morphing an inheritance graph. So in your example your virtual inheritance is ubiquitous.
An explanation:
ex: (non virtual)
class Inheritable;
class DerivedA : public Inheritable;
class DerivedB : public Inheritable:
class Common : public DerivedA, public DerivedBIn this inheritance graph both DerivedA and DerivedB have to implement their own unique instance of Inheritable. Therefore, if Common tried to use a member function (or variable) of Inheritable, the compiler would need to know whether to lookup the function in either the DerivedA or DerivedB classes, since both these classes have valid (identical code, yet separate) function implementations. The compiler would give an ambiguity error if you tried to call Inheritable::AFunction() from inside Common. This is fixed by specifying either DerivedA::AFuntion() or DerivedB::AFuntion() when calling AFunction inside Common.
ex: (virtual)
class Inheritable;
class DerivedA : public virtual Inheritable;
class DerivedB : public virtual Inheritable:
class Common : public DerivedA, public DerivedBNow Inheritable is inherited virtually. The inheritance graph is changed so that DerivedA and DerivedB share the same implementation of Inheritable. I.E. there is only onle implmentation of Inheritable. This resolves the ambiguity described above: Inheritable::AFunction() is a valid call from Common. However, now you need to now that DerivedA and DerivedB can each change the state of Inheritable (i.e. member variables). Therefore you need to make sure that DerivedA and DerivedB dont unexpectedly interfere with each other.
As far as the virtual function is concerned in the above virtual example, if DerivedA and DerivedB both override a virtual function in inheritable, an ambiguity issue will arise similar to above non-virtual example.
Essentially, to keep things simple, dont virtually inherit a class with virtual functions that are overriden in the derived classes. (Read that ten times fast.)
invalid namespace anyone

![]() |
SQL Insert Query question
|
C++ String Project?
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |