answersLogoWhite

0

When is a virtual base class useful in c plus plus?

Updated: 8/17/2019
User Avatar

Wiki User

11y ago

Best Answer

Consider the following class declarations:

class Base{...};

class Intermediate1: public Base{...};

class Intermediate2: public Base{...};

class Derived: public Intermediate1, public Intermediate2{...};

Here, Derived indirectly inherits two instances of Base, one from Intermediate1 and the other from Intermediate2. This introduces an ambiguity when implicitly referring to Base from Derived. We must explicitly refer to Intermediate1::Base or Intermediate2::Base. Not only that but since there are two instances of Base, they consume twice as much memory.

Clearly it would be better if there were only one instance of Base shared between Intermediate1 and Intermediate2. This isn't always possible, but if we assume that it is possible in this case, we need to allow Derived to inherit directly from Base and for Intermediate1 and Intermediate2 to both share that same instance, virtually. We do this by declaring Base to be virtually inherited by both Intermediate1 and Intermediate2:

class Base{...};

class Intermediate1: public virtual Base{...};

class Intermediate2: virtual public Base{...};

class Derived: public Intermediate1, public Intermediate2{...};

Now there's only one instance of Base which is directly inherited by Derived. Thus when Derived, Intermediate1 or Intermediate2 implicitly refer to their Base class, they will implicitly refer to Derived::Base. Moreover, any objects we subsequently derive from Derived will inherit directly from Base themselves, but it remains the one and only instance of Base in the hierarchy.

Note that the virtual keyword can be placed before or after the access specifier, it makes no difference (both methods are shown above). Note also that the virtual keyword is only of relevance to Derived and its derivatives. It does not affect any non-derived instances of Intermediate1 nor Intermediate2 -- they still inherit directly from Base.

I mentioned earlier that it isn't always possible to make use of virtual base classes. It all depends on the purpose of the classes involved and what members they have. Generally, the fewer members in the base class the better, so abstract base classes are often good candidates for virtual base classes. Ultimately, all derivatives must be capable of sharing the same instance of the virtual base class.

User Avatar

Wiki User

11y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: When is a virtual base class useful in c plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions

What is a virtual base class in C plus plus when the different methods in base and derived classes have the same name true or false?

False. A virtual base class is one that is common to two or more derived classes that are themselves base classes, and that may be combined through multiple inheritance. By declaring the common base class to be virtual in its direct derivatives, only one instance of the common base class exists in the multiple-inheritance classes.


What is the order of construction and destruction in c plus plus?

The least-derived base classes are always constructed first, in the order specified by the derived class inheritance list. The most-derived class (the one you are actually instantiating) is always constructed last. Destruction is basically the reverse of construction. However, base class destructors must be declared virtual to ensure that the most-derived class destructor is called first, regardless of which class destructor is actually invoked. That is, if you hold a pointer to a base class that has no virtual destructor, deleting that pointer will only destroy the base class, not the derived class, leaving the derived class in an invalid state (because it no longer has an underlying base class) and with no way to recover the memory it consumes. It is important to remember that if you declare any virtual methods within a class, you must also declare the destructor virtual. A class without a virtual destructor is not intended to be derived from. If it has virtual methods, but no virtual destructor, it is not well-formed and must not be used as a base class.


What is inheritance in visual c plus plus?

When you derive one class from another, the derived class inherits the sum of all the public and protected members exposed by the class it derives from. The underlying class is known as a base class and in the class hierarchy is an ancestor of the derived class. It is not necessary for the base class to know any of the details regarding its derivatives, as prudent use of virtual methods ensures the derived class acts correctly even when calling methods in the base class.


How do you implement inheritance in c plus plus?

You implement inheritance by deriving a new class of object from an existing class of object. The existing class is known as the base class of the derived class.Classes declared final cannot be used as bases classes and classes without a virtual destructor (or a virtual destructor override) cannot be used as polymorphic base classes.


Write abstract class in c plus plus?

An abstract class is any class definition that contains at least one pure-virtual function. class AbstractClass { public: virtual void DoSomething()=0; // Pure-virtual. };


What is the difference between Virtual Base Class and Abstract Class in c plus plus?

You might as well compare apples and oranges. The only thing they have in common is that they are both base classes (just as apples and oranges are both fruit). An abstract base class is an abstract data type (ADT). An ADT is defined as any class that declares one or more pure virtual functions. This prevents anyone from instantiating objects from the class other than through derivation. The derivative must implement all pure-virtual methods declared in its base class, otherwise it becomes an ADT itself. Once a derivative overrides a pure-virtual method, that method becomes virtual with respect to all subsequent derivatives. However, only derivatives that provide or inherit a complete implementation for the sum of all pure-virtual methods can physically be instantiated. A virtual base class is a base class that is inherited virtually. That is, if class A is declared a virtual base class of class B, then any derivative of B will automatically inherit directly from A. This is useful in multiple inheritance where two or more intermediate classes are themselves derived from a common base class. Normally, the most-derived class will inherit one instance of the common base class from each of the intermediate base classes. By declaring the common base class to be virtual in the intermediate classes, the most-derived class inherits just one instance of the common base class, which is then shared amongst the intermediate classes. Thus if class A inherits from classes B and C and they each inherit from D, then there will be two instances of D in the hierarchy (A::B::D and A::C::D). This introduces ambiguity when referring directly to A::D. But if B and C inherit from D virtually, then there is only one instance of D (A::D), and both B and C derive from this one, shared instance, virtually. This removes any ambiguity and reduces the overall footprint of the hierarchy by eliminating redundant instances of the shared base class. Ideally, virtual base classes should have little or no data members.


Explain virtual functions in C plus plus?

A virtual function in C++ is a function that can have multiple definitions.For example:If you have a class which contains a virtual function:class Virtual{virtual void makesomething();};That function can be implemented when you inherit that class an implement the function. So:class Inherit : public Virtual{//this is the same function, but can be implemented to do something differentvoid makesomething() { //do something else }};


What is the difference between base class and derived class in c plus plus?

There is no difference other than that a derived class inherits from a base class. That is, the derived class inherits all the public and protected members of its base class, and is a more specialised form of its base class. Thus both can be treated as if they really were base classes. The derived class can also override the virtual methods of the base class, thus allowing polymorphic behaviour without the need to know the exact type of the derived class.


What is meant by function overriding in c plus plus?

Function overriding applies to class member functions (methods), where a derived class provides a more specialised implementation of its generic base class method. An override can still call the base class method and augment it with other instructions (before or after the call to the base class method), or it can provide a complete implementation of its own without calling the base class method. Classes that are intended to act as generic base classes will generally declare their methods to be virtual, meaning they are intended to be overridden, if required. Abstract base classes will contain one or more pure-virtual methods (which may or may not provide a generic implementation), meaning classes must be derived from the abstract base class and all the pure-virtual methods must be overridden in the derived class (otherwise they, too, become abstract). Only classes that fully implement all the pure-virtual methods they inherit from their base classes can actually be instantiated. That is, you cannot instantiate an instance of an abstract base class, even if it provides generic implementations for all its pure-virtual methods. They can only be instantiated by deriving classes from them.


Why constructers can not be inherrited in c plus plus?

Every class of object must provide its own specific construction code. Since they are not really functions they cannot be overridden, thus they cannot be inherited. The same applies to the class destructor and the class self-assignment operator. Each class must handle these explicitly, within the class implementation. They cannot be implemented outside of the class, and therefore cannot be inherited. Although the virtual keyword can be applied to the destructor, it's not a function and therefore not a virtual function. The only reason for having a virtual destructor at all is when one or more of the class methods are virtual. Since classes with virtual methods are intended to act as generic interfaces for more specialised implementations, it's important that when destroying such a class that the most-derived (or most-specialised) class is destroyed first, working up the hierarchy to the base class which must always be destroyed last. This can only be achieved through virtual destruction. Failure to declare the base class destructor virtual could result in a base class being destroyed (such as when deleting a pointer to it), which would then result in an incomplete and therefore invalid derived class remaining in memory.


Conventional base class in c plus plus?

A conventional base class is a class that has a virtual destructor. Virtual destructors are important in most class hierarchies because while we may not always know the exact type of the most-derived class in a hierarchy, we will always know at least one of its base classes. If we destroy that base, it is reasonable to expect the entire object to be destroyed, not just the base, and this can only be achieved with a virtual destructor.Note that a virtual destructor must be declared in the least-derived class in the hierarchy to ensure correct polymorphic behaviour.Classes not intended to be used as base classes do not have virtual destructors. This does not mean they cannot be used as base classes, but if you choose to use them as base classes you must be aware of the "unconventional" problems that can arise, particularly when destroying objects through pointers or references to their base classes as will lead to resource leaks.If you do not wish a class to be used as a base class, then the class should be declared final (since C++11). All other classes can still be used as base classes, however only classes with virtual destructors behave polymorphically.Typically, if we define at least one virtual function in a class, we should also define a virtual destructor for that class. However, derived classes implicitly inherit virtual destructors from their bases thus the absence of a virtual destructor in a derived class should not be taken to mean the derived class is not intended to be used as a base class; always look at the least-derived class definition to determine if a virtual destructor exists or not.Along with the final specifier, the overridespecifier was also introduced in C++11. This makes it much easier to document virtual functions and their overrides. That is, we can use the virtual specifier solely to introduce a new virtual function into the class hierarchy, and use the overridespecifier to show that we are explicitly overriding a virtual function rather than simply introducing a new virtual function. We can also use the final specifier to indicate that an individual virtual function cannot be overridden any further:struct X {virtual void f ();virtual ~X ();};struct Y : X {void f () override; // implies X::f() is either virtual or is itself an override~Y () override; // implies ~X() is virtual or is itself an override};struct Z : Y {void f () override; // implies Y::f() is either virtual or is itself an override~Z () override; // implies ~Y() is virtual or is itself an override};The override and final keywords are only useful if used consistently. However, being part of the language itself means we can now enlist the help of the compiler to catch subtle errors that couldn't be easily caught before:struct X {void f () override; // error! X did not inherit an f () thus it cannot be an override!virtual void g (); // okvirtual ~X(); // ok};struct Y : X {void g () override final; // ok~Y () override; // ok};struct Z : Y {void g () override; // error! Y::f() is declared final -- it cannot be overridden!~Z () override; // ok};struct Z2 : Z final {}; // okstruct Z3 : Z2 {}; // error: Z2 is final -- cannot be used as a base class!


Type of inheritances in c plus plus?

Single, multiple, multi-level, hierarchical and hybrid/virtual inheritance. Single inheritance applies when one class inherits from just one base class. Multiple inheritance applies when one class inherits from two or more base classes. Multi-level inheritance applies to a class that inherits from at least one base class that is itself derived from another base class. Hierarchical inheritance applies to a base class that is inherited by two or more separate derived classes. Hybrid inheritance combines multiple inheritance, multi-level inheritance and hierarchical inheritance. That is, where A is a common base class of derived classes B and C, and B and C are both base classes of derived class D. Hybrid inheritance is often used with virtual inheritance where B and C inherit from A virtually rather than directly. In these cases, the virtual base class is instantiated by the most-derived class in the hierarchy, D, and this instance is then shared by both B and C.