473,395 Members | 1,680 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

virtual member function in constructor

Hi,

I have just encountered a problem when calling a virtual member function
in a constructor.
Only the memberfunction of the parent class is called instead of the
overloaded function.

I have attached a small example.

Is that bug or feature. If feature: is there an easy way to get the
behaviour as I am looking for?

Thanks

Karsten

#include <iostream>
using namespace std;
class A {
public:

virtual A(){init();}
virtual ~A(){}
virtual void init(){
cout << "class A::init\n";
}
void test(){init();}

};

class B: public A{
public:
B():A(){}
virtual ~B(){}
virtual void init(){
cout << "class B::init\n";
}
};

int main(int,char**){
// only class A's init is called
B b;

// works as I expected
b.test();
return 0;

}
Jul 22 '05 #1
7 1781
Oops,

the 'virtual' in front of the constructor was just desparate try I
forgot to remove before attaching the file...

Karsten Hochkirch wrote:
Hi,

I have just encountered a problem when calling a virtual member
function in a constructor.
Only the memberfunction of the parent class is called instead of the
overloaded function.

I have attached a small example.

Is that bug or feature. If feature: is there an easy way to get the
behaviour as I am looking for?

Thanks

Karsten

------------------------------------------------------------------------

#include <iostream>
using namespace std;
class A {
public:

virtual A(){init();}
virtual ~A(){}
virtual void init(){
cout << "class A::init\n";
}
void test(){init();}

};

class B: public A{
public:
B():A(){}
virtual ~B(){}
virtual void init(){
cout << "class B::init\n";
}
};

int main(int,char**){
// only class A's init is called
B b;

// works as I expected
b.test();
return 0;

}


Jul 22 '05 #2

"Karsten Hochkirch" <K.*********@vbew.net> wrote in message
news:bv**********@online.de...
Hi,

I have just encountered a problem when calling a virtual member function in a constructor.


Within a constructor, virtual calls are resolved using the vtable of
the class in which the constructor is defined, rather than the vtable
of the fully derived type of the object being constructed. Therefore,
you must be very careful when calling virtual functions from
constructors; in particular, the possibility of calling a pure virtual
function exists.

Jonathan
Jul 22 '05 #3

"Karsten Hochkirch" <K.*********@vbew.net> wrote in message news:bv**********@online.de...

Is that bug or feature. If feature: is there an easy way to get the
behaviour as I am looking for?


That is the way it is supposed to work. For the duration of the execution of the
the constructor body, the dynamic type of the object is considered to be that of
the constructor that is running. The primary reason is that the derived class has
yet to be initialized (the base class constructor is run first), so you don't want to
be roaming around in the derived code.

The work around is to place any virtual function based common initialization in
a base class member function other than the constructor and then call it from
the derived constructor.

The same thing happens for destructors (just in the reverse order).

Jul 22 '05 #4
Karsten Hochkirch wrote:
Oops,

the 'virtual' in front of the constructor was just desparate try I
forgot to remove before attaching the file...

Karsten Hochkirch wrote:
Hi,

I have just encountered a problem when calling a virtual member
function in a constructor.
Only the memberfunction of the parent class is called instead of the
overloaded function.

I have attached a small example.

Is that bug or feature. If feature: is there an easy way to get the
behaviour as I am looking for?

Thanks

Karsten

this is not really a feature, this is the way things are supposed to
happen... When the constructor's called, the object does not exist yet :
so the code of your overloaded virtual method is unknown and unreachable
; thus, only the one of the parent class can be called.
(a funny thing you can do once you've understood this, is to use it to
call code of a pure virtual method)
the tip I'd told you is to never call any method in a constructor, and
if needed, to provided an init() that should be called by the programmer
(not as you're doing in your code sample, where init() is called from
the ctor)
Jul 22 '05 #5
On Fri, 30 Jan 2004 15:31:10 -0500, "Ron Natalie" <ro*@sensor.com> wrote:

"Karsten Hochkirch" <K.*********@vbew.net> wrote in message news:bv**********@online.de...

Is that bug or feature. If feature: is there an easy way to get the
behaviour as I am looking for?

[Correct explanation of why, snipped.]

See also the FAQ:
<url: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.3>
The work around
Actually there are many different workarounds.

The most common workarounds are also in the FAQ (I'm happy to take much credit
for their inclusion, although credit for the text goes to Marshall Cline):

<url: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.4>
is to place any virtual function based common initialization in
a base class member function other than the constructor and then call it from
the derived constructor.


This only seems to allow virtuality for one level of class derivation.

It's not a commonly used workaround.

I don't recommend it, but perhaps it should be included among the others in
the FAQ?

Jul 22 '05 #6
On Fri, 30 Jan 2004 21:21:34 +0100 in comp.lang.c++, Karsten Hochkirch
<K.*********@vbew.net> was alleged to have written:
I have just encountered a problem when calling a virtual member function
in a constructor.
Only the memberfunction of the parent class is called instead of the
overloaded function.


This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[23.3] When my base class's constructor calls a virtual function on its
this object, why doesn't my derived class's override of that virtual
function get invoked?" It is always good to check the FAQ before
posting. You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/
Jul 22 '05 #7
Ok, I think I understand by now.
Thanks to all of you for the anwers!!
Jul 22 '05 #8

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

Similar topics

6
by: Thomas Matthews | last post by:
Hi, Is placing the keyword "virtual" in front of a constructor allowed as in the sample below? class TTable { virtual TTable(); }; My compiler, Borland Builder 5.2, has system libraries
18
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 } };
22
by: Ruben Van Havermaet | last post by:
Hi, I have a problem using member functions in derived classes that override virtual member functions of base classes. The following pieces of (simplified) code don't work. Can anybody give...
10
by: PengYu.UT | last post by:
Hi, A pure function is called in the base function constructor. It generate a run time error: "pure virtual method called". My problem is that class A have some derived classes. I want A's...
7
by: dc | last post by:
Can anybody think of a situation where virtual function's address resolution/ something related to virtual is done at compile time
16
by: plmanikandan | last post by:
Hi, I have doubts reg virtual constructor what is virtual constructor? Is c++ supports virtual constructor? Can anybody explain me about virtual constructor? Regards, Mani
11
by: ypjofficial | last post by:
Hello All, So far I have been reading that in case of a polymorphic class ( having at least one virtual function in it), the virtual function call get resolved at run time and during that the...
1
by: Bart Simpson | last post by:
Can anyone explain the concept of "slicing" with respect to the "virtual constructor" idiom as explain at parashift ? From parashift: class Shape { public: virtual ~Shape() { } ...
17
by: Jess | last post by:
Hello, If I have a class that has virtual but non-pure declarations, like class A{ virtual void f(); }; Then is A still an abstract class? Do I have to have "virtual void f() = 0;"...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.