answersLogoWhite

0


Best Answer

Virtual means that decision would be taken at another stage... first base class constructor is called and construction of object cannot be held anonymous. that's y virtual constructors are not possible.

AnswerOne reason is that a constructor cannot be virtual is because it is the constructor's job to fill in the v-table for virtual functions. If a constructor was allowed to be virtual, then you end up with kind of a chicken and egg paradox. In order to call the constructor, the compiler would have to look in the v-table to find where the constructor is located. Unfortunately, it's the constructor's job to place the address of virtual functions (which would include itself) into the v-table. Without RTTI, it would be impossible to resolve which child's constructor to call. In most cases, a virtual helper function that the constructor calls is more then enough.
User Avatar

Wiki User

12y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

10y ago

C++ does not support virtual constructors because it doesn't have to and was never intended to. Ask yourself what a virtual constructor would actually achieve and you'll realise why they are completely unnecessary.

When you instantiate a derived class you would rightly expect the base class to be constructed first but this is the complete opposite of how a virtual function behaves. When you call a base class' virtual method you would rightly expect the derived class' override to be called (if one is provided). The same goes for virtual destruction. If you destroy the base class of a derived class you expect the derived class to be destroyed before the base class. But in construction you expect the complete opposite, and you get that for free just by inheriting from a base class.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

A virtual function in C++ is a class method that can be overridden in a child class, and then be resolved at run-time using a pointer to the class that is not restricted to pointing to just that class type.

This is done by providing a vtable, or virtual table, of function addresses in a static array for the class. (The alternative, non-virtual, requires compile-time binding of the function address.)

Virtual functions allow objects to act polymorphically without the overhead of expensive runtime type information. That is, each derived object should exhibit its own specific behaviours according to its type, without any prior knowledge of what that type is; each object should simply "do the right thing" without being specifically told what to do.

By way of an example, suppose you wish to model a farm with cows, sheep and pigs. You could create separate classes for each, but it would make more sense to treat them generically: all your animals eat, walk on four legs, have birth dates and ages, and are either male or female. So much of the implementation could be handled by a single class, such as "animal", and everything common to all your animals can be handled by this one class. Your separate classes can then devote themselves to the differences between these animals, such as their habitats, their food, the products they produce (milk and beef, mutton and lamb chops, pork and bacon, etc), and even the sounds they make (moo, bah and oink).

When you pass an animal to a function, you would rightly expect that animal to act according to its actual type. That is, if the function were to invoke the animal's "make_sound" method, then you would rightly expect a cow to moo. But how can the function do this without knowing the type of animal that was passed to it?

One solution would be to use dynamic_cast to determine the animal's runtime type information. For instance, if we dynamically cast to a cow and the return type is non-null, then we know we definitely have a cow and we can call its "moo" method directly. But this means we must test for each known type until the return is non-null before we can call the specific method. Worse, if we later decide we want to create a zoo and extend our animal classes accordingly we then have to test for those types as well. And if someone else decides they want to derive animals that we haven't even considered, our class will quickly breaks.

A better solution would be to the objects themselves decide exactly what they are and have them act accordingly -- polymorphically. This is achieved through virtual functions. If we declare animal::make_sound() to be a virtual function, all our derived classes automatically inherit this method and are expected to override it with their own specific implementations. Thus the cow::make_sound() method might call the cow::moo() method or it could provide the entire implementation in the cow::make_sound() method itself. Either way, when you call animal::make_sound() you invoke the cow::make_sound() method if the animal is a cow, or the pig::make_sound() method if the animal is a pig. There is no longer any need to know the exact type of the object; not now nor in the future: you simply call a generic method and in return you get a specific implementation, automatically.

While virtual functions do a have a cost, most of that cost is paid when you declare the first virtual function which creates the virtual table that decides which specific methods will be called according to the object's actual runtime type, but without the overhead of runtime type information (which is required with dynamic cast). More importantly, if someone later decides to derive a tiger from your animal class, they will be expected to provide their own tiger::make_sound() method and implement it accordingly. You've provided the generic framework, they simply need to fill in the blanks.

Pure-virtual functions are no different to virtual functions other than in key one respect: while virtual functions are only expected to be overridden, pure-virtual functions must be overridden. And since animal::make_sound() can't really be expected to provide a meaningful implementation other than an error, it would make sense for this method to be declared pure-virtual, thus ensuring all derivatives provide a specific implementation. The only other real difference is that pure-virtual functions need not provide a generic implementation, whereas virtual functions must provide one.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

A constructor is specific to the class in which it is declared. Inheriting a constructor would make no sense to a derived class. The base class' default constructor is called automatically when a derived class is instantiated. Base classes are always constructed first, from the lowest level up. Once the base classes are fully constructed, the derived class can complete the construction via its own constructor.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

The simple answer there is no need for one. Aside from anything else, a virtual function implies the function can be overridden by a derived class, which would result in the most-derived function being called first, with no guarantee the base class function will ever be called. But with constructors, the least-derived constructor must always be called first, in the same sequence they are declared in the inheritance lists of all derivatives. The destructor can, and indeed should be declared virtual, since the most derived destructor must always be called first, the complete reverse of construction. The only time a destructor need not be declared virtual is when there are no other virtual functions, meaning the class is not intended to be derived from at all. You can still derive from it, but it won't behave polymorphically, which can only lead to serious problems with dangling references during destruction.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

It would not make any sense to allow virtual constructors. When a class hierarchy is constructed, the least-derived class must always be constructed first, working down the hierarchy to the most-derived class. This makes sense because a derived class cannot exist until its base class has been fully constructed. But this is the complete opposite of how virtual functions operate. When you call a base class virtual method you would rightly expect the most-derived override to be executed, not the least-derived method.

Virtual destruction makes sense because derived objects are destroyed in the reverse order of their construction. Thus if you explicitly destroy a base class, you rightly expect the most-derived class to be destroyed first, working back up the hierarchy to eventually destroy the lest derived class. This can only be achieved by declaring the least-derived class destructor virtual. If you don't declare it virtual, you end up destroying the class you're actually referring to, but the remainder of the class hierarchy will remain in memory but will be completely invalidated by the destruction of one of its classes.

Moreover, constructors are always specific to the class in which they are declared. That is, it would not make any sense to allow a derived class to override a base class constructor. A derived class can explicitly invoke a specific base class constructor via the derived class' initialisation list, but it cannot override that constructor. After all, it has no business constructing objects it knows absolutely nothing about besides the protected and public interface. And nor should it. The same applies to base classes not knowing the specific of their derivatives, since it would be impossible to predict what classes might be derived from your classes in the future. Hence the need to declare virtual functions, and a virtual destructor. The only reason they do not default to being virtual in the first place is because not all classes are intended to be derived from, in which case the added overhead of a class v-table would be detrimental to performance and memory consumption.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

You should declare a virtual destructor in any class that has one or more virtual methods besides the destructor. Such classes are intended to act as base classes, and this ensures the most-derived destructor is always called first, whenever an instance of a base class is explicitly destroyed.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

Constructors are not functions as such, they merely describe the initialisation phase of a class. Since they are only of relevance to the classes in which they are declared, there is no need nor want to inherit them. Every class must define its own constructors, which can include calls to any base class constructors from within the derived class initialisation list (if no list is declared, or a base class constructor omitted, then the default constructor is called instead).

Class destructors are also not functions as such, but if the class has any virtual methods, or the class is not prevented from acting as a base class, the destructor must be virtual. This is simply to ensure that when a base class object is destroyed, its derived class destructor is called first. If the destructor were not virtual, destroying a base class would not destroy the derived class, leaving it in an undefined state.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

Without virtual functions, it would be impossible to use objects polymorphically. Polymorphism is a one of the four pillars of object oriented programming, the other three being encapsulation, inheritance and abstraction.



Consider the following example, which has no virtual functions but does have an overridden method:


#include


class base

{

public:

void print(){ std::cout << " is a base class." << std::endl; }

};


class derived : public base

{

public:

void print(){ std::cout << " is a derived class." << std::endl; }

};


int main()

{

base b;

std::cout << "b";

b.print();


derived d;

std::cout << "d";

d.print();


base *p = &d;

std::cout << "p";

p->print();


return( 0 );

}



Output:


b is a base class.

d is a derived class.

p is a base class.


Something's clearly not right because although base class b and derived class d correctly identify themselves as such, p, which points to d, is effectively saying that d is a base class, which is demonstrably not the case.


Note that it doesn't matter that p was declared to be a pointer to a base class because derived is a kind-of base class, thus it is legal to point at an instance of derived. But it is a derived class nonetheless, so we would rightly expect p to identify itself as such.


One way of addressing this problem is to statically downcast p to the correct type, by replacing the following line:


p->print();


With the following line:


((derived*)p)->print();


While this fixes the immediate problem, it's highly dangerous to statically downcast like this. In this particular instance we know for certain that p really is a derived class, but this type of solution would not work if d were some other derivative of base. If we are lucky, our program will simply crash, but that's hardly an ideal situation.


A dynamic downcast would obviously be better (if the returned pointer is NULL, you'll at least know the downcast failed, thus allowing you the opportunity to handle the error), but you cannot dynamically downcast non-polymorphic objects. The derived class is certainly a kind-ofbase class, but that does not automatically make it polymorphic.


The correct way to deal with this problem is to make the derived class polymorphic. We do this by declaring the base::print() method to be a virtual method.


class base

{

public:

virtualvoid print(){ std::cout << " is a base class." << std::endl; }

virtual ~base(){}

};


With this new declaration in place, we can safely call p->print() without the need to explicitly downcast (whether statically or dynamically). Our derived class is behaving as expected, polymorphically, and more importantly, automatically.


Note that if your class has one or more virtual methods, the class destructor must be virtual as well, as shown in the modified declaration above. This becomes vital when we instantiate derived classes on the heap using base class pointers. When we come to destroy those base class pointers, we expect the derived classes to be destroyed first. If the base class destructor is non-virtual, only the base class will be destroyed, leaving us with an otherwise avoidable memory leak.


Note also that we do not need to explicitly declare derived::print() as being a virtual function as it is implied through inheritance. However, it is good practice to include the virtual keyword in all derived class overrides, if only to remind you of the fact it is a virtual function.


The above example serves to demonstrate why we need virtual functions: to automatically extract expected behaviour, polymorphically, from our derived classes, even if we only have a pointer or reference to one of their base classes.


Note that polymorphism has a cost in terms of memory consumption in order to accommodate the virtual table (or vtable) which essentially lists each virtual function's actual memory address, as determined by the object type at the point of instantiation. However, the bulk of that cost is paid as soon as you declare the first virtual function. Thereafter, you are simply extending the table and the cost is minimal.


The only other way to leverage polymorphic behaviour without virtual functions is to use static downcasting, which is dangerous at best. You could, of course, use runtime information to determine the actual type prior to a static downcast, but runtime information is way more expensive than virtual functions, and will not only increase your code size, but will also make your code that much more difficult to maintain. And while there while there may well be times when you will be absolutely certain a static downcast will work, do not be tempted to do so. The whole point of having a virtual table is to allow the object itself to work out its actual type -- via the virtual table -- thus easing the burden upon the programmer.


The main advantage of virtual functions and polymorphism in general is that you do not need to know the actual type in advance. This becomes even more important when other programmers derive classes from your classes. You cannot possibly downcast to a type you know absolutely nothing about, even with runtime information. Virtual functions will release that potential with the absolute minimum possible cost.



Pure-virtual Function


To round off, pure-virtual functions are similar to virtual functions, but where a virtual function may be overridden, a pure-virtual function must be overridden. When you declare a pure-virtual function, you render your class abstract (an abstract data type, or abstract base class), which means you cannot instantiate object of that type, you can only derive new object from that type. This also means that a derivative that does not provide an implementation for all the pure-virtual functions it inherits becomes abstract itself. However, any implementations it does provide can be inherited by its derivatives. The base class that originally declared the pure-virtual method needn't provide an implementation, but even if it does that method cannot be inherited. The whole point of abstraction is to provide a generic interface, thus ensuring all derivatives provide their own specialised implementations.


For instance, a shape class is a good candidate for abstraction because shapes are conceptual objects from which you could derive any shape, such as circles, squares and triangles. However, because a shape is a conceptual object you cannot implement a shape::draw() method, thus you must make it pure-virtual. This ensures every derivative of shape provides its own specific draw() method. Thus if you have a collection of shape pointers you can simply call their individual draw() methods one by one, without regard to the actual type of shape (including derived shapes which you yourself did not design and therefore cannot foretell). Each shape simply does what is expected of it, because every shape is guaranteed to have a draw() method -- and if it didn't, it couldn't possibly exist!


This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Why do you use virtual functions in C plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

How do you represent a C plus plus non-pure virtual function in UML?

All virtual functions (including pure-virtual functions) are represented in italics. All non-virtual functions are represented normally. There is no differentiation between pure and non-pure virtual functions, however some people append "=0" to distinguish the pure-virtual functions.


What keyword is used to find derivative in C plus plus?

The lazy way is to use a dynamic cast. The correct way is to use virtual functions in the base class. That way you don't ever need to know the derived type -- it simply does what is expected of it.


Does the C plus plus programming language use a virtual machine?

No, it does not. But Microsoft Visual Studio 2008 allows you to connect to a virtual machine and run your projects "sandboxed".


Why functions are not used in c plus plus?

Of course they are used. Both stand-alone and class-member functions are used in C++.


Why Member functions are not virtual by default?

It depends which language you are using. Java member functions are virtual by default but C++ member functions are not. Java takes the viewpoint that if any member function is declared virtual then all member functions should be declared virtual, so they may as well be virtual by default. However, C++ takes the view that a member function should only be declared virtual if there's a specific reason to declare it virtual. Not all functions are meant to be overridden. Indeed, not all classes are meant to act as base classes. So all member functions are non-virtual by default. Purists will argue that the C++ method is the correct method. After all, there's no point in having a virtual-table if it's never going to be used. Java places the onus on the programmer to eliminate an unused virtual-table, whereas C++ simply doesn't provide one unless you explicitly declare one. However, the real reason C++ uses non-virtual methods by default is because it has to maintain compatibility with a C struct. A C struct is not a class so it has no methods (and therefore no virtual methods). It is a "plain-old-data" or POD structure. In C++, however, a struct is a class. As such, by default, it has a compiler-generated default constructor, default copy and move constructors, default copy and move assignment operators and a default destructor. It also has public access by default. However, because the compiler-generated methods are all trivial member-wise implementations, a C++ struct is backwardly compatible with a POD. Thus C code can use a C++ struct just as if it were a C struct, because both use POD structures by default. If C++ used virtual member functions by default, a struct would not be a POD by default, it would be a base class by default.

Related questions

How do you represent a C plus plus non-pure virtual function in UML?

All virtual functions (including pure-virtual functions) are represented in italics. All non-virtual functions are represented normally. There is no differentiation between pure and non-pure virtual functions, however some people append "=0" to distinguish the pure-virtual functions.


What keyword is used to find derivative in C plus plus?

The lazy way is to use a dynamic cast. The correct way is to use virtual functions in the base class. That way you don't ever need to know the derived type -- it simply does what is expected of it.


Can there be friend functions in c plus plus?

Yes, there can be friend functions in C++.


Does the C plus plus programming language use a virtual machine?

No, it does not. But Microsoft Visual Studio 2008 allows you to connect to a virtual machine and run your projects "sandboxed".


How dynamic binding acheived in c plus plus?

Dynamic binding is achieved via virtual functions and the virtual table that is associated with every class that declares or inherits a virtual function. The virtual table (or v-table) maps every virtual function (including pure-virtual functions) to a function pointer that points to the most-derived overload. This makes it possible to invoke specific behaviour even when the runtime type of the object is unknown to the caller.


Printf and scanf Operators in C and C plus plus?

No, they are functions. Operators are -> or ++or /=


Why functions are not used in c plus plus?

Of course they are used. Both stand-alone and class-member functions are used in C++.


Why Member functions are not virtual by default?

It depends which language you are using. Java member functions are virtual by default but C++ member functions are not. Java takes the viewpoint that if any member function is declared virtual then all member functions should be declared virtual, so they may as well be virtual by default. However, C++ takes the view that a member function should only be declared virtual if there's a specific reason to declare it virtual. Not all functions are meant to be overridden. Indeed, not all classes are meant to act as base classes. So all member functions are non-virtual by default. Purists will argue that the C++ method is the correct method. After all, there's no point in having a virtual-table if it's never going to be used. Java places the onus on the programmer to eliminate an unused virtual-table, whereas C++ simply doesn't provide one unless you explicitly declare one. However, the real reason C++ uses non-virtual methods by default is because it has to maintain compatibility with a C struct. A C struct is not a class so it has no methods (and therefore no virtual methods). It is a "plain-old-data" or POD structure. In C++, however, a struct is a class. As such, by default, it has a compiler-generated default constructor, default copy and move constructors, default copy and move assignment operators and a default destructor. It also has public access by default. However, because the compiler-generated methods are all trivial member-wise implementations, a C++ struct is backwardly compatible with a POD. Thus C code can use a C++ struct just as if it were a C struct, because both use POD structures by default. If C++ used virtual member functions by default, a struct would not be a POD by default, it would be a base class by default.


What is a method in c plus plus?

In C++, methods are simply class member functions.


Which desktop application use c plus plus?

There are very few applications of any note that aren't written in C++ (or some combination of C++ and C). Even the Java virtual machine required to interpret Java programs is written in C++.


What is the difference between C and C plus plus prototypes?

The only difference is that C does not use nor require prototypes. C++ does because all functions and types must at least be declared, if not defined, before they can be used.


C plus plus library functions for string operations?

You can use "string" class in C++ for string operations or you may use c style string functions as well. #include &lt;string&gt; String class in C++ provides all basic function to operate on strings. you may details descriptin at http://www.cplusplus.com/reference/string/string/