473,699 Members | 2,715 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

virtual functions

We can have virtual destructors.Why we can't have virtual constructors?

Mar 28 '06 #1
7 2558
va*******@gmail .com posted:
We can have virtual destructors.Why we can't have virtual constructors?

'Cause they'd be redudant. A constructor is called once: upon
construction of the object. An object is contructed as follows:

TypeName object_name;

Therefore, the compiler knows straight away which contructor should be
called, and therefore need not consult any v-table.

-Tomás
Mar 28 '06 #2
va*******@gmail .com wrote:
We can have virtual destructors.Why we can't have virtual constructors?


Because for virtual functions (including the destructor), the system
determins the dynamic type of the object to find out which function to call
at runtime. But a constructor is called to create the object, so there is
no dynamic type to find out yet.

Mar 28 '06 #3
We have virtual destructors because of run time polymorphism. Consider
following example,

class Base {

char *p;

Base() {
p = new char[20];
}

~Base() {

delete[] p;

}

};

class Derived: public Base {

char *t;

Derived() {
t = new char[20];
strcpy (t,p);
}

~Derived() {
delete[] t;
}

};

Now if you declare a Base class pointer

Base *b = new Derived();

and then do
delete b;

it will call Base class destructor instead of derived class destructor
since Base class desctructor is not virtual. This will keep memory
allocated to t and never free up. Also, if p is being used by derived
class, it will be freed by Base class destructor before derived class
is destroyed.

If we declare Base class destructor as virtual, then derived class
destructor will be called first and then Base class destructor.

As for constructor not being virtual, you would not want to use p in
derived class before it is allocated in Base class. Base class
constructor should be called first and then derived class.

Hope this helps.

Tejas Kokje
Code Monkey
http://mailmount.sf.net

Mar 28 '06 #4
Rolf Magnus wrote:
va*******@gmail .com wrote:
We can have virtual destructors.Why we can't have virtual constructors?


Because for virtual functions (including the destructor), the system
determins the dynamic type of the object to find out which function to
call at runtime. But a constructor is called to create the object, so
there is no dynamic type to find out yet.


That's not "why", it just states what the current mechanism is.

The compiler always knows the type of the fully-formed object at
construction time. So C++ could have been defined as constructing the
complete virtual method jump table first, instead of last. Then
constructors could freely call virtual methods into the derived classes,
and the result would be virtual construction.

The reason we can't upgrade the current language to support that feature is
too much code depends on constructors calling virtual methods that don't
dispatch to their derived overrides. The work-around might be "Coplien's
Curiously Recurring Template Pattern".

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 28 '06 #5
* Phlip:
Rolf Magnus wrote:
va*******@gmail .com wrote:
We can have virtual destructors.Why we can't have virtual constructors? Because for virtual functions (including the destructor), the system
determins the dynamic type of the object to find out which function to
call at runtime. But a constructor is called to create the object, so
there is no dynamic type to find out yet.


That's not "why", it just states what the current mechanism is.


Right you are, so far.

In at least one situation the C++ abstract machine is capable of finding
a relevant static function based on an object's dynamic type (namely, a
deallocation function, 'operator delete'), and in like manner the
language could technically have supported virtual constructors, either
with some run-time checking of argument types, or corresponding checking
of an assumed signature against the actual dynamically found signature,
or simply requiring some fixed, generic signature.

The compiler always knows the type of the fully-formed object at
construction time. So C++ could have been defined as constructing the
complete virtual method jump table first, instead of last. Then
constructors could freely call virtual methods into the derived classes,
and the result would be virtual construction.
In one sense of "virtual construction", yes: that's the way it works in
Java and C#.

But this is something very different from calling a constructor virtually.

Instead, it's all about virtual calls from a constructor.

The reason we can't upgrade the current language to support that feature is
too much code depends on constructors calling virtual methods that don't
dispatch to their derived overrides.
No, the reason that we can't downgrade to the Java/C# model is that we
want to preserve type safety, where type safety includes the notion of
class invariants; see the FAQ at <url:
http://www.parashift.c om/c++-faq-lite/strange-inheritance.htm l#faq-23.5>.

The reason why we, in practice, can't upgrade C++ to directly support
virtual constructors, virtual calls of constructors, is that this would
extend the language a great deal for something that can easily be
achieved within the language as-is, namely via clone functions.

For those who are not familiar with clone functions, see the FAQ, <url:
http://www.parashift.c om/c++-faq-lite/virtual-functions.html# faq-20.8>.

The work-around might be "Coplien's Curiously Recurring Template Pattern".


That's one of several work-arounds for implementing something akin to
the Java/C# model; see the FAQ at <url:
http://www.parashift.c om/c++-faq-lite/strange-inheritance.htm l#faq-23.6>.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 28 '06 #6
Alf P. Steinbach wrote:
But this is something very different from calling a constructor virtually.

Instead, it's all about virtual calls from a constructor.


Correct. I'm playing language inventor. I tell my teeming minions that y'all
can't get virtual constructors, but I will give you virtual method calls
from within constructors, because they are just as useful. And per your FAQ
citation, they are indeed dangerous, but that never stopped C++ before. And
the FAQ citation doesn't say why we _can't_ downgrade to the Java system,
just why we won't.

Also The Standard sez that constructors are "not functions", so I don't want
to go against whatever else that implies. Subconstructor notation,
try{}catch wrappers, and who knows what else.

So the ultimate "why" is probably going to be "because" here...

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 28 '06 #7
I am unable to undestand why we need virtual constructor.
As when we create some object we know the type of object and call that
constructor so why need virtual const.
In decst..case we can have a case where derived object is pointed by a
pointer of base class and we use delete to release memory. and if it
would be virtual distructor then only it can call proper derivced class
const...

Corect me if I am wrong

Mar 29 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
4425
by: vijay | last post by:
I have a doubt with size of classed with virtual functions I have declared A,A1,A2 ,B , C, D some classes with no varaibles but a vitual function each, The size of A is as expected 4 bytes with one vtbl ptr BUt when I derive the class B from class A (both have 1 virtual function each ) the size remains still as 4 bytes . class A = 4 bytes class B :public A = 4 bytes class...
5
2922
by: Ryan Faulkner | last post by:
Hi, Im having a few problems with virtual functions (Im using the Visual C++ environment by the way). I have a base class with three virtual functions and a derived class with a single new virtual function plus redefinitions of the three inherited virtual functions. Following is a simplified code fragment to illustrate my code and my problem:
18
2214
by: nenad | last post by:
Wouldn't it be nice if we could do something like this: class Funky{ public: auto virtual void doStuff(){ // dostuff } };
19
2337
by: qazmlp | last post by:
class base { // other members public: virtual ~base() { } virtual void virtualMethod1()=0 ; virtual void virtualMethod2()=0 ; virtual void virtualMethod3()=0 ;
7
1679
by: Aguilar, James | last post by:
I've heard that virtual functions are relatively ineffecient, especially virtual functions that are small but get called very frequently. Could someone describe for me the process by which the address of a virtual function is resolved and what the hidden costs associated with virtual functions are? I've heard the same of typeof (that it is inefficient if used in high traffic code) -- if you've the time, could you explain how typeof works...
25
5414
by: Stijn Oude Brunink | last post by:
Hello, I have the following trade off to make: A base class with 2 virtual functions would be realy helpfull for the problem I'm working on. Still though the functions that my program will use a lot are the ones that are virtual and thus will slow down the calculation, at least that is what what I have read on several places on the internet. It makes sense the program has to work with some kind off lookup table for the virtual...
11
4357
by: santosh | last post by:
Hello, I was going through the Marshal Cline's C++ FAQ-Lite. I have a doubt regarding section 33.10. Here he is declaring a pure virtual destructor in the base class. And again defining it inline. Like this.
7
313
by: ashishnh33 | last post by:
i want to know about the concept behind the virtual functions.
5
1990
by: Dilip | last post by:
In a polymorphic hierarchy is it common practice to have public virtual functions in the base class with a default empty implementation and let the derived classes decide whether they want to override it or not? In such cases what would be the access levels of those functions in both base and derived classes? struct AbstractBase { virtual void mandatory_func() = 0; virtual void optional_func() { }
14
4207
by: v4vijayakumar | last post by:
Why we need "virtual private member functions"? Why it is not an (compile time) error?
0
8685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6532
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.