answersLogoWhite

0


Want this question answered?

Be notified when an answer is posted

Add your answer:

Earn +20 pts
Q: What is Need of virtual class while building class hierarchy?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

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!


Difference between base class and derived class?

The derived class derives, or inherits, from the base class. The derived class is like a "child", and the base class, the "parent". The child class has the attributes of the parent class - its variables (those defined at the class level) and methods. Changes done to the parent class (the base class) will affect the child class (the derived class).


What is the virtual keyword used for in C plus plus?

Virtual functions (or virtual methods as they are also known), are methods declared in a class that are expected to be overridden by a derived class. That is, the method is a generic method that applies to the class in which it is declared (the base class), but that may require modification by a more-specialised class (the derived class). When you implicitly call the base class method, the overridden method is called instead, thus ensure the correct behaviour. The overridden can still call the base class method explicitly, as can any other code that has access to the base class method.If you do not declare generic methods to be virtual, overriding those methods in the derived class may have unexpected side-effects, particularly if the method is overloaded in the base class. For instance, a derived class' override will effectively hide all the overloads of the base class.Note that if you declare any virtual function, then you are essentially notifying the end-user that the class is intended to act as a generic class and may be derived from, if required. However, if the function is declared pure-virtual, you are notifying the end-user that the class is abstract and mustbe derived from (it is not optional).Also, if there are any virtual methods then the destructor must be virtual as well, to ensure the derived object is destroyed before the base class is destroyed.It is often good practice to declare all methods as virtual if there's at least one virtual method, however this only applies to methods that would require alternative handling by more-specialised classes. If the base class can provide a complete implementation that requires no further specialisation, it needn't be declared virtual.Although there is a memory cost involved in declaring virtual methods, the bulk of that cost is paid with the first virtual function which establishes the virtual table (v-table). Thereafter, the cost is minimal. The v-table ensures the most-derived method is called, thus ensuring correct behaviour of derived classes, even when working with the generic base class.


What is the primary value in using virtual functions within C plus plus?

Virtual methods are member methods of a base class that can be overridden by derived classes. Classes that can act as base classes should contain all the functionality that is common to all their derived classes. However, the derived classes may need to alter that functionality in some way by overriding the methods in the base class. While this is fine when we actually hold pointers or references to a derived object, what happens when we hold pointers or references to the base class of a derived object? We cannot call the overridden methods explicitly unless we expose the runtime class of the derived object, which would incur an unacceptable processing overhead. Virtual methods allow us to get around this problem in a more elegant fashion. By declaring a method as virtual, calling the method implicitly on a base class will automatically and explicitly call the most-derived implementation in the class hierarchy. If no override exists, the base class method is called explicitly. While this mechanism incurs a memory penalty in creating the v-table (virtual table), the bulk of that cost is paid with the first virtual method declared. Subsequent methods add very little overhead, so it is not uncommon for programmers to declare all methods virtual. However, if there is at least one virtual method declared, the class destructor must also be declared virtual. Thereafter, you should only declare other methods to be virtual if there is an actual need to do so. After all, there's no point in consuming more memory than is actually required. Sometimes it is not possible for a base class to provide the implementation for a virtual method, In this case the method should be declared pure-virtual. The same rules apply as for virtual functions, however you can no longer instantiate objects from the base class itself -- it becomes an abstract class -- so you must derive from it and you must provide an implementation for all the pure-virtual methods (otherwise it becomes abstract itself). Abstract classes will generally have few, if any, member variables, and all member methods will generally be declared as pure-virtual. Abstract classes are primarily intended to provide a common interface to their derivatives. The base class can still provide default implementations for pure-virtual methods, however they must be explicitly called. In some cases, a derived class will simply augment the default implementation, rather than override it completely. Be aware that base classes that are common to derived classes that can be used by multiple inheritance classes will introduce ambiguities. The multiple inheritance class will inherit two or more instances of the common base class, and therefore must be called explicitly from the multiple inheritance class. However, it is possible to remove the ambiguity altogether, by declaring the common base class to be virtual in its immediate derivatives, in which case all derivatives share the same common base class when multiply inherited. Ideally, the common base class should have very little in the way of implementation, and few, if any, member variables.


What is the need of virtual base classes in c plus plus?

Virtual functions are advantageous in that they allow us to write code in a more generic fashion more easily than would otherwise be possible. More importantly, without virtual functions, polymorphic behaviour would be impossible to achieve. Consider the following example: #include<iostream> struct instrument { virtual ~instrument() {} virtual void play () =0; }; void foo (instrument& a, instrument& b) { a.play(); b.play(); } struct drum : instrument { void play () override { std::cout << "Playing a drum\n"; } }; struct guitar : instrument { void play () override { std::cout << "Playing a guitar\n"; } }; int main() { drum d; guitar g; foo(d, g); } Output: Playing a drum Playing a guitar There are several things to note about this program. As you know, in C++, all types must be declared before they can be used. However, note that the foo function was defined before the drum and guitar classes were declared and yet it was perfectly able to invoke their specific methods even without a forward declaration. This is made possible because the function knows about the instrument class and that's all it really needs to know about; the instrument class exposes the precise interface required by the foo function. Note also that the instrument class has a virtual destructor. Unless a class is marked final, a virtual destructor tells us that we may derive a new class from this class. In other words, it tells us that this class can be used as a base class. It is important to note that every class that declares one or more virtual methods MUST also have a virtual destructor. I shall explain why shortly. The instrument::play() method is a virtual method. The '=0' suffix denotes that the function is pure-virtual. Not all base classes require pure-virtual methods, but in this case we do because the instrument class is a conceptual class rather than a concrete class. That is, it is an abstract object; one we can imagine exists but cannot physically exist in reality. By declaring at least one pure-virtual method, we prevent end-users from constructing objects from the class. A pure-virtual method may or may not be implemented by its base class, but it must be implemented by its derivatives otherwise they become abstract themselves. By contrast, virtual methods must be implemented in the base class but need not be implemented by the derived classes. Whenever we declare a method virtual, we guarantee that the most-derived override for that method will always be invoked. Thus when we construct a drum object, its play() method becomes the most-derived override. This is how the foo function was able to invoke drum::play() despite the fact it only knew of the existence of the instrument::play() method. Indeed, the foo function doesn't even know that a refers to a drum any more than b refers to a guitar. All it needs to know is that they are both types of instrument and that is guaranteed by the compiler because both drum and guitar are derived from instrument. While it is true that every drum is an instrument, it is not true that every instrument is a drum (it could be a guitar). How does the foo function know which of the two overrides to invoke? That's precisely the type of problem virtual functions help to resolve. Every class in a hierarchy has a virtual function table (or v-table) which maps the virtual functions of the base class to the most-derived overrides of those functions. Thus when play() is invoked against an object, the class v-table determines the correct function address according to the actual runtime type of the object. While the v-table does consume additional memory over and above the size of the class members, the cost is minimal (approximately two words per virtual method). However, sometimes it becomes necessary to "switch on" the runtime type of an object in order to evoke specific behaviour. For instance, suppose our drum object has the following interface: struct drum : instrument { void play () override { std::cout << "Playing a drum\n"; } void play_rimshot () { std::cout << "Playing a rimshot\n"; } void play_side_stick () { std::cout << "Playing a sidestick\n"; } }; The play_rimshot and play_sidestick methods are too specialised to be placed in the instrument class. The instrument class exists to provide a common interface to all instruments but you cannot play a rimshot or sidestick upon a guitar. If these methods were part of the instrument interface then they'd also be part of the guitar interface. One way to invoke these specific behaviours is to dynamically cast the instrument to a drum. If the cast succeeds, you can definitely invoke these methods. If not, then you cannot. But runtime type information is expensive and is often the result of poor design. It is not that there's anything wrong with having such specialised methods, it is only that accessing them from a generic interface is generally the wrong way to go about invoking them. In this particular case all we really need to do is derive a new class from the drum class to cater for these more specific methods: struct rimshot : drum { void play() override { "Playing a rimshot\n"; } }; struct sidestick : drum { void play() override { "Playing a sidestick\n"; } }; Even though these classes did not exist when we first wrote our foo function, the function can still cater for them: rimshot r; sidestick s; foo (r, s); In other words, virtual functions have not only enabled runtime polymorphism without the need for runtime type information, they have also provided some measure of future-proofing our code; we do not need to continually maintain the foo function in order to cater for new behaviours.

Related questions

What is the difference between abstarct class and virctulfunction in C sharp?

They are not comparable, but may have some relationship between them.An abstract class is a class, while a virtual function (or method) is a method. A method must exist within a class. Hence, a class has methods, and the methods may be defined as virtual functions.A virtual function must be defined in a class, but that class does not have to be an abstract class. However, the purpose of a virtual function in C# is to provide a default behavior/implementation, while allowing the derived class to override that default implementation, hence it makes no sense to define a virtual function in a sealed class (a leaf, that is, no class can extend from it, and it is not an abstract class)Example:public class Parent {public virtual string MostCommonPhrase() {return "You better listen to me...";}}public class Child : Parent {public override string MostCommonPhrase() {return "You never listen to me...";}}


What is abrstac class and virctulfunction in c sharp?

abstract class is a class label with abstract. It is just like a common class, with the following characterics: 1. Abstract class cannot be instantiate with an instance. 2. Abstract class may have abstract methods, while the normal class cannot have abstract methods. a virtual function in C# is a way to provide a default implementation for the class hierarchy. Both abstract class and common class (not sealed) can have virtual methods/ functions. Note that an abstract method (of an abstract class) is defining the intent, no codes (no default behavior), the implementation are left for the derived classes to do so. The virtual function if defined in an abstract class must define the implementation, the minimum is to do nothing: public abstract class Vehicle { public abstract int GetNumberOfTires(); public virtual void Move() { // default is doing nothing} } public class Car : Vehicle { public override int GetNumberOfTires() { return 4; } public override void Move() { throws new OutOfFuelExpection(); } }


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!


Difference between base class and derived class?

The derived class derives, or inherits, from the base class. The derived class is like a "child", and the base class, the "parent". The child class has the attributes of the parent class - its variables (those defined at the class level) and methods. Changes done to the parent class (the base class) will affect the child class (the derived class).


What is the virtual keyword used for in C plus plus?

Virtual functions (or virtual methods as they are also known), are methods declared in a class that are expected to be overridden by a derived class. That is, the method is a generic method that applies to the class in which it is declared (the base class), but that may require modification by a more-specialised class (the derived class). When you implicitly call the base class method, the overridden method is called instead, thus ensure the correct behaviour. The overridden can still call the base class method explicitly, as can any other code that has access to the base class method.If you do not declare generic methods to be virtual, overriding those methods in the derived class may have unexpected side-effects, particularly if the method is overloaded in the base class. For instance, a derived class' override will effectively hide all the overloads of the base class.Note that if you declare any virtual function, then you are essentially notifying the end-user that the class is intended to act as a generic class and may be derived from, if required. However, if the function is declared pure-virtual, you are notifying the end-user that the class is abstract and mustbe derived from (it is not optional).Also, if there are any virtual methods then the destructor must be virtual as well, to ensure the derived object is destroyed before the base class is destroyed.It is often good practice to declare all methods as virtual if there's at least one virtual method, however this only applies to methods that would require alternative handling by more-specialised classes. If the base class can provide a complete implementation that requires no further specialisation, it needn't be declared virtual.Although there is a memory cost involved in declaring virtual methods, the bulk of that cost is paid with the first virtual function which establishes the virtual table (v-table). Thereafter, the cost is minimal. The v-table ensures the most-derived method is called, thus ensuring correct behaviour of derived classes, even when working with the generic base class.


Examples of inheritance in c plus plus?

Single-inheritance is where one class inherits directly from another class: class A {}; class B : public A {}; Here, class B inherits all the public and protected members of class A. Multiple-inheritance is where one class inherits directly from two or more classes: class A {}; class B {}; class C : public A, public B {}; Here, class C inherits all the public and protected members of both A and B. Multi-level inheritance is where one class inherits from another class that itself derived. class A {}; class B : public A {}; class C : public B {}; Here, class B inherits all the public and protected members of A while class C inherits all the public and protected members of B, including those inherited from A. Virtual inheritance applies to multi-level inheritance whereby a virtual base class becomes a direct ancestor to the most-derived class. This variation of inheritance is typically used in multiple inheritance situations where two or more intermediate classes inherit from the same base class: class A {}; class B : public virtual A {}; class C : public virtual A {}; class D : public B, public C {}; Here, classes B and C both inherit from class A. Without virtual inheritance this would mean class D would inherit two instances of A (B::A and C::A), thus creating ambiguity when referring to D::A. By employing virtual inheritance, D inherits directly from A, and both B and C inherit from D::A. In other words, B and C share the same instance of A. Another use of virtual inheritance is when you need to make a class final. class A; class B { friend class A; B() {} // private constructor }; class A : public virtual B { }; Here, class A is the final class. Class B is a helper class that has a private constructor while class A is declared a friend of class B. Class A is therefore the only class that can inherit from class B as it is the only class that can construct objects from class B. However, by inheriting class B virtually, we ensure that no other class can be derived from class A because virtual inheritance ensures that the most-derived class must be able to construct a class B object first. Currently, only class A has that privilege and must always be the most-derived class.


Why did Gandhi's wife so object to cleaning the latrine?

She was opposed to the cleaning of the latrines because she deemed it the work of the Untouchables, who were considered the lowest class of the social hierarchy in India, while she herself was part of the highest class of the social hierarchy. Gandhi, however, let her know that no work was beneath them and he promoted equality amongst all Indians, regardless of the caste system.


What is the primary value in using virtual functions within C plus plus?

Virtual methods are member methods of a base class that can be overridden by derived classes. Classes that can act as base classes should contain all the functionality that is common to all their derived classes. However, the derived classes may need to alter that functionality in some way by overriding the methods in the base class. While this is fine when we actually hold pointers or references to a derived object, what happens when we hold pointers or references to the base class of a derived object? We cannot call the overridden methods explicitly unless we expose the runtime class of the derived object, which would incur an unacceptable processing overhead. Virtual methods allow us to get around this problem in a more elegant fashion. By declaring a method as virtual, calling the method implicitly on a base class will automatically and explicitly call the most-derived implementation in the class hierarchy. If no override exists, the base class method is called explicitly. While this mechanism incurs a memory penalty in creating the v-table (virtual table), the bulk of that cost is paid with the first virtual method declared. Subsequent methods add very little overhead, so it is not uncommon for programmers to declare all methods virtual. However, if there is at least one virtual method declared, the class destructor must also be declared virtual. Thereafter, you should only declare other methods to be virtual if there is an actual need to do so. After all, there's no point in consuming more memory than is actually required. Sometimes it is not possible for a base class to provide the implementation for a virtual method, In this case the method should be declared pure-virtual. The same rules apply as for virtual functions, however you can no longer instantiate objects from the base class itself -- it becomes an abstract class -- so you must derive from it and you must provide an implementation for all the pure-virtual methods (otherwise it becomes abstract itself). Abstract classes will generally have few, if any, member variables, and all member methods will generally be declared as pure-virtual. Abstract classes are primarily intended to provide a common interface to their derivatives. The base class can still provide default implementations for pure-virtual methods, however they must be explicitly called. In some cases, a derived class will simply augment the default implementation, rather than override it completely. Be aware that base classes that are common to derived classes that can be used by multiple inheritance classes will introduce ambiguities. The multiple inheritance class will inherit two or more instances of the common base class, and therefore must be called explicitly from the multiple inheritance class. However, it is possible to remove the ambiguity altogether, by declaring the common base class to be virtual in its immediate derivatives, in which case all derivatives share the same common base class when multiply inherited. Ideally, the common base class should have very little in the way of implementation, and few, if any, member variables.


How did Songhai social hierarchy differ from medieval hierarchy?

Like the Medieval social structure, there were very stark contrasts between the rich and poor in the Songhai Empire. Monarchs were at the top while landless slaves formed the base of the social hierarchy. However, there is one distinct way Songhai differed from Medieval social structure, Songhai religious officials were not considered a separate social class.


What is virtual inheritance?

Virtual inheritance is used in multiple inheritance hierarchies whenever two or more classes inherit from the same base class. For example, consider the following minimal example: struct A {int x;}; struct B : A {}; struct C : A {}; struct D : B, C {}; Here, A is a common base class of both B and C, thus B::A and C::A are independent instances of A. However, D inherits from both B and C thus indirectly inherits both B::A and C::A. This introduces an ambiguity when implicitly referring to A from D, as in the following example: D d; d.x = 42; // error: ambiguous When the compiler sees this it won't know whether we are referring to B::A.x or C::A.x, thus we must be explicit when referring to A via D: d.B::x = 42; // ok The problem with this is that we still have two separate instances of x so unless we are extremely careful about which x we are referring to we can easily end up with two different values for x with no way of knowing which was the correct value with respect to D. What we really need is for B and C to share the same instance of A and we achieve that through virtual inheritance: struct A {int x;}; struct B : virtual A {}; struct C : virtual A {}; struct D : B, C {}; D d; d.x = 42; // ok Note that d.x can be referred to as d::A.x, d::B::A.x or d::C::A.x because they all refer to the same instance of x, thus the ambiguity is eliminated. In effect, the most-derived class in the hierarchy (D) is now a direct descendant of A rather than an indirect descendant of both B::A and C::A. Note also that the virtual keyword has no effect on independent instances of either B or C because they then become the most-derived classes within their own hierarchy and therefore behave exactly as they would had the virtual keyword been omitted. The virtual keyword only comes into play when we derive from a class with a virtual base. It is also possible to have a base class that is both virtual and non-virtual in the same hierarchy: struct A {int x;}; struct B : virtual A {}; struct C : virtual A {}; struct D: A {} struct E : B, C, D {}; Here, A is a virtual base of both B and C, as before, but not of D. Thus E::A implicitly refers to the virtual A while E::D::A must be explicitly referred to as E::D::A because it is a separate instance. Such classes are best avoided, but if we don't have access to the source code we sometimes don't have a choice in the matter. However, if a base class holds no data it really doesn't matter whether it is declared virtual or not because a class that has no data consumes just one byte regardless of how many instances there are.


What is the process of inheritance in c plus plus?

There are two ways to create a new class from an existing class (and thus make use of the existing code without duplicating that code). We can either embed an instance of the existing class as a member of the new class or we can derive the new class from the existing class. The former method is known as composition while the latter is known as inheritance. Composition is necessary when the member is a fundamental (built-in) data type but can also be applied to user-defined types while inheritance can only be applied to user-defined types. Although a class may inherit from any user-defined type, some classes are not intended for this purpose thus they can only be used in compositions. In order to derive a new class from an existing class, the existing class must be a base class. The minimum definition of a base class is that the class must have a virtual destructor. Fundamental types have neither a constructor nor a destructor, hence they cannot act as base classes. Base classes typically have one or more virtual methods thus if you declare any virtual methods you must also declare a virtual destructor. Note that, unlike Java where all methods are virtual by default, C++ methods are always non-virtual by default. When you derive a new class from a base class, the new class inherits all the public and protected methods of the base class, but none of the private members nor any friends of the base class. Virtual methods of the base class are methods that are expected to be overridden by its derivatives. If the base class is an abstract base class it will also have one or more pure virtual methods. These methods must be overridden by a derivative otherwise that derivative becomes abstract also. Derived classes may also act as base classes. You may also override non-virtual methods, however these are not treated as overrides. These have the affect of "hiding" the base class implementation and will prevent polymorphic behaviour. Polymorphism is achieved through virtual methods. When a virtual method is implicitly invoked, the most-derived override of that method is automatically invoked, regardless of the source of the call. This makes it possible for a base class to invoke the more specific behaviour of its own derivative without requiring any specialised knowledge about those derivatives. In other words, it allows us to write code in a more generic manner, catering for new types of derivative that do not yet exist. Those types inherit all the generic methods and can specialise those methods as required. In some cases we may wish to prevent any further specialisation of a particular method. To do so we can specify that the override is final. If we derive a new class from this class and attempt to override a final method, a compiler error will tell us that this is illegal. We can also use this facility to prevent any further specialisation of a class by declaring the class itself as final. All methods that are declared virtual in a base class are implicitly virtual in the derived class, whether overridden or not. Therefore we can override those methods without explicitly declaring them virtual. Although it is considered good programming practice to explicitly include the virtual specifier in an override, C++11 allows us to explicitly use the override specifier instead, thus providing a visual clue that the method was inherited rather than merely declared virtual. Note that when a base class declares a virtual destructor, the derived class destructor is implicitly virtual as well (including the compiler-generated default destructor). However, destructors are not functions per se and are not inherited as such. However, the virtual aspect of the destructor is required to ensure that an object is destroyed in the correct sequence. If you hold a pointer to a base class object and destroy that object, the most-derived object in the inheritance hierarchy must be destroyed first -- which is why the destructor must be virtual. If it were not declared virtual, only the base class would be destroyed, which would leave an incomplete derived object in memory, which would inevitably result in undefined behaviour should you later attempt to destroy that derivative. Note that the destruction sequence of a derived object is the complete opposite of the construction sequence. To construct a derived object, its least-derived base class constructor must be invoked first. This is why constructors can never be declared virtual. In addition to the constructors, an object's copy assignment operator (and its move move assignment operator in C++11) cannot be declared virtual either. Each class of object must define their own operator or use the compiler-generated default operator.


What is the need of virtual base classes in c plus plus?

Virtual functions are advantageous in that they allow us to write code in a more generic fashion more easily than would otherwise be possible. More importantly, without virtual functions, polymorphic behaviour would be impossible to achieve. Consider the following example: #include<iostream> struct instrument { virtual ~instrument() {} virtual void play () =0; }; void foo (instrument& a, instrument& b) { a.play(); b.play(); } struct drum : instrument { void play () override { std::cout << "Playing a drum\n"; } }; struct guitar : instrument { void play () override { std::cout << "Playing a guitar\n"; } }; int main() { drum d; guitar g; foo(d, g); } Output: Playing a drum Playing a guitar There are several things to note about this program. As you know, in C++, all types must be declared before they can be used. However, note that the foo function was defined before the drum and guitar classes were declared and yet it was perfectly able to invoke their specific methods even without a forward declaration. This is made possible because the function knows about the instrument class and that's all it really needs to know about; the instrument class exposes the precise interface required by the foo function. Note also that the instrument class has a virtual destructor. Unless a class is marked final, a virtual destructor tells us that we may derive a new class from this class. In other words, it tells us that this class can be used as a base class. It is important to note that every class that declares one or more virtual methods MUST also have a virtual destructor. I shall explain why shortly. The instrument::play() method is a virtual method. The '=0' suffix denotes that the function is pure-virtual. Not all base classes require pure-virtual methods, but in this case we do because the instrument class is a conceptual class rather than a concrete class. That is, it is an abstract object; one we can imagine exists but cannot physically exist in reality. By declaring at least one pure-virtual method, we prevent end-users from constructing objects from the class. A pure-virtual method may or may not be implemented by its base class, but it must be implemented by its derivatives otherwise they become abstract themselves. By contrast, virtual methods must be implemented in the base class but need not be implemented by the derived classes. Whenever we declare a method virtual, we guarantee that the most-derived override for that method will always be invoked. Thus when we construct a drum object, its play() method becomes the most-derived override. This is how the foo function was able to invoke drum::play() despite the fact it only knew of the existence of the instrument::play() method. Indeed, the foo function doesn't even know that a refers to a drum any more than b refers to a guitar. All it needs to know is that they are both types of instrument and that is guaranteed by the compiler because both drum and guitar are derived from instrument. While it is true that every drum is an instrument, it is not true that every instrument is a drum (it could be a guitar). How does the foo function know which of the two overrides to invoke? That's precisely the type of problem virtual functions help to resolve. Every class in a hierarchy has a virtual function table (or v-table) which maps the virtual functions of the base class to the most-derived overrides of those functions. Thus when play() is invoked against an object, the class v-table determines the correct function address according to the actual runtime type of the object. While the v-table does consume additional memory over and above the size of the class members, the cost is minimal (approximately two words per virtual method). However, sometimes it becomes necessary to "switch on" the runtime type of an object in order to evoke specific behaviour. For instance, suppose our drum object has the following interface: struct drum : instrument { void play () override { std::cout << "Playing a drum\n"; } void play_rimshot () { std::cout << "Playing a rimshot\n"; } void play_side_stick () { std::cout << "Playing a sidestick\n"; } }; The play_rimshot and play_sidestick methods are too specialised to be placed in the instrument class. The instrument class exists to provide a common interface to all instruments but you cannot play a rimshot or sidestick upon a guitar. If these methods were part of the instrument interface then they'd also be part of the guitar interface. One way to invoke these specific behaviours is to dynamically cast the instrument to a drum. If the cast succeeds, you can definitely invoke these methods. If not, then you cannot. But runtime type information is expensive and is often the result of poor design. It is not that there's anything wrong with having such specialised methods, it is only that accessing them from a generic interface is generally the wrong way to go about invoking them. In this particular case all we really need to do is derive a new class from the drum class to cater for these more specific methods: struct rimshot : drum { void play() override { "Playing a rimshot\n"; } }; struct sidestick : drum { void play() override { "Playing a sidestick\n"; } }; Even though these classes did not exist when we first wrote our foo function, the function can still cater for them: rimshot r; sidestick s; foo (r, s); In other words, virtual functions have not only enabled runtime polymorphism without the need for runtime type information, they have also provided some measure of future-proofing our code; we do not need to continually maintain the foo function in order to cater for new behaviours.