virtual constructors?

R

rahul8143

hello,
i want to know that is virtual constructors possible? if not why?
also does virtual destructors functions are often used in C++
programming.
regards,
rahul.
 
R

Rolf Magnus

hello,
i want to know that is virtual constructors possible?
No.

if not why?

Because a virtual function call is dynamically dispatched to an object's
actual class. A constructor is called when an object gets created. At this
time, the class is well known, it wouldn't make sense to call the
constructor of another class instead, and there would be no way for the
runtime system to know which other class to dispatch it to.
also does virtual destructors functions are often used in C++
programming.

Yes.
 
J

Jerry Coffin

hello,
i want to know that is virtual constructors possible? if not why?
also does virtual destructors functions are often used in C++
programming.

A virtual function dispatches a function based on the actual type of
object being pointed at/referred to. Until the object exists (after the
ctor finishes execution) there IS no object whose type can be
determined.

If you ever destroy an object of a derived class via a pointer to a
base class, the destructor needs to be virtual. For example, this code
gives undefined behavior:

class base {};
class derived : public base {};

// ...
base *b = new derived;
// ...
delete b;

To get defined behavior, you need code more like this:

class base {
virtual ~base() {}
};

class derived : public base {};

// ...
base *b = new derived;
// ...
delete b;

In cases like this, the destructor is often defined only to make it
virtual, so it's fairly common for the destructor's body to be empty.
 
A

Alf P. Steinbach

* Thomas Tutone:
A constructor's job is to transform raw memory into a well-defined object.
Before that there is no object to dispatch a virtual call to a constructor,
and after that you cannot call a constructor again on this object (at least
not without using very low-level language features). That's the basic C++
constructor guarantee, that an object of type T receives one and only one T
constructor call, and that that happens before anything else.

See also
<url:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.4>.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,779
Messages
2,569,606
Members
45,239
Latest member
Alex Young

Latest Threads

Top