bug-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: virtual function in destructor


From: Gabriel Dos Reis
Subject: Re: virtual function in destructor
Date: 22 Apr 2001 20:49:27 +0200

address@hidden (Steffen Jahn) writes:

| Hi,
| 
| another strange behavior is the handling of virtual 
| functions in desctructors. Please take a look at the
| examples below.
| 
| The first example causes no problems.
| 
| struct A
| {
|   ~A(void) { f() ; }
|   virtual void f(void) = 0 ;

This is undefined-behaviour were A::f -not- defined.

| void main() { B b ; }
| 
| And g++ (linker) complains:
| 
| /usr/bin/ld:
| Unresolved:
| A::f(void)
| collect2: ld returned 1 exit status

This is correct behaviour, assuming A::f were not defined.

| As a work around, you have to use virtual function
| only in the class scope (inline) in destructors.

No, both examples lead to undefined behaviour if A::f is not defined. 

In constructors and destructor, the dynamic type of an object equates
its static type, meaning that the virtual fonction is statically
resolved to A::f. 

In practice, that means you don't want to call virtual functions in
constructors/destructor unless you know what you're doing.

-- Gaby



reply via email to

[Prev in Thread] Current Thread [Next in Thread]