Calling member function in ctors and dtors.

B

BigMan

Is it safe to call nonvirtual member functions from ctors and dtors?
What about virtual ones?
 
P

Pete Becker

Is it safe to call nonvirtual member functions from ctors and dtors?
What about virtual ones?

Yes, it's safe. Unlike Java, C++ has a safe rule for virtual functions:
when a constructor or destructor calls a virtual function it calls the
function defined for the type whose constructor or destructor is
currently being run, which isn't necessarily the most derived type.
 
R

Ron Natalie

Pete said:
Yes, it's safe. Unlike Java, C++ has a safe rule for virtual functions:
when a constructor or destructor calls a virtual function it calls the
function defined for the type whose constructor or destructor is
currently being run, which isn't necessarily the most derived type.
With the exception of virtual calls to pure virtual functions in the constructors
(these are undefined).
 
P

Peter Koch Larsen

Ron Natalie said:
With the exception of virtual calls to pure virtual functions in the
constructors
(these are undefined).

Hi Ron

This is a slight surprise to me as i read it that pure virtual functions can
be called in destructors. Was that the intended meaning and if so - what is
the result?

/Peter
 
M

msalters

Ron said:
With the exception of virtual calls to pure virtual functions in the constructors
(these are undefined).

And destructors, 10.4/6, and it also includes indirect calls.

The reason is that pure virtual functions don't have to appear in
vtables.
The vtable entries will be overwritten by the derived constructor, as
every pure virtual function must be defined later, in a derived class.
Non-virtual calls don't use vtables, and therefore are defined.

(Implementations which don't use vtables are still bound by the same
rules. )

HTH,
Michiel Salters
 
R

Ron Natalie

Peter said:
Hi Ron

This is a slight surprise to me as i read it that pure virtual functions can
be called in destructors. Was that the intended meaning and if so - what is
the result?
That is the intended meaning and it is what the standard says.
It is undefined behavior to make a virtual call to a pure virtual
function in a constructor or destructor (even if it has an implementation).
 
P

Pete Becker

Ron said:
With the exception of virtual calls to pure virtual functions in the
constructors
(these are undefined).

As I said, it calls the function defined for the type whose contructor
or destructor is currently being run. In a class that has a pure virtual
function with no definition the function is not defined.
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top