f



Avoid virtual function when calling common code in destructor

Hello,

I have a class with a logical disconnect() function. This disconnect
function may be called manually and will be called in the destructor.
However, I'm not quite sure how to build this function.  I want the
disconnect() function to be virtual, but calling a virtual function
from a destructor is faux pas, correct?  Is it okay in this situation,
or otherwise, how can I do this?

Thank you,
Kevin


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
1/12/2005 8:55:32 PM
comp.lang.c++.moderated 10738 articles. 1 followers. allnor (8506) is leader. Post Follow

4 Replies
363 Views

Similar Articles

[PageSpeed] 0

Kevin Grigorenko wrote:
> Hello,
>
> I have a class with a logical disconnect() function. This disconnect
> function may be called manually and will be called in the destructor.
> However, I'm not quite sure how to build this function.  I want the
> disconnect() function to be virtual, but calling a virtual function
> from a destructor is faux pas, correct?  Is it okay in this situation,
> or otherwise, how can I do this?

There's nothing wrong with calling a virtual function in a destructor,
however, the function will resolve as if the type of the object is
of the type of the destructor.

The thing you can't do is make a virtual call to a PURE VIRTUAL
function in a destructor.

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Ron
1/13/2005 12:05:57 PM
Calling a virtual function from a destructor calls the function in the
current object. You have to write your disconnect() so that it behaves
well when it is called during destruction.

struct A {
virtual void disconnect() {} //#1
virtual ~A() { disconnect(); } //Calls #1 while destruction
};

struct B : public A {
virtual void disconnect() {} //#2
virtual ~B() { disconnect(); } //Calls #2 while destruction
};


--lsu


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
L
1/13/2005 4:38:19 PM
On 12 Jan 2005 15:55:32 -0500, Kevin Grigorenko  
<kevin.grigorenko@gmail.com> wrote:

> I have a class with a logical disconnect() function. This disconnect
> function may be called manually and will be called in the destructor.
> However, I'm not quite sure how to build this function.  I want the
> disconnect() function to be virtual, but calling a virtual function
> from a destructor is faux pas, correct?  Is it okay in this situation,
> or otherwise, how can I do this?

First, you might consider to get rid of disconnect function, placing all  
cleanup in destructors. This could be the best solution with regards to  
implementation effort.

Second, the context implies that you use interface based design. If this  
is so, you may want to employ proxy design pattern or handle-envelope (aka  
pimpl) idiom, that is, you wrap all your objects with a proxy object that  
calls disconnect function from its destructor.

Example:

     struct resource
     {
         virtual void do_some() = 0;
         virtual void disconnect() = 0;
         virtual ~resource() {}
     };

     struct resource_proxy
     {
         typedef std::auto_ptr<resource> wrapped_ptr;
         wrapped_ptr const w_; // const here makes resource_decorator  
noncopyable

         // forwarding functions
         void do_some() { w_->do_some(); }
         void disconnect() { w_->disconnect(); }

         resource_proxy(wrapped_ptr w) : w_(w) {}
         ~resource_proxy() { this->disconnect(); }
     };

Client functions only deal with resource_proxy, which is initialized with  
some concrete resource object from your resource hierarchy.

-- 
Maxim Yegorushkin

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Maxim
1/13/2005 8:03:03 PM
Ron Natalie wrote:
> Kevin Grigorenko wrote:
>>I have a class with a logical disconnect() function. This disconnect
>>function may be called manually and will be called in the destructor.
>>However, I'm not quite sure how to build this function.  I want the
>>disconnect() function to be virtual, but calling a virtual function
>>from a destructor is faux pas, correct?  Is it okay in this situation,
>>or otherwise, how can I do this?
> 
> There's nothing wrong with calling a virtual function in a destructor,
> however, the function will resolve as if the type of the object is
> of the type of the destructor.

It's debatable whether calling a virtual function is 'correct' in
a destructor; for example, when you consider the OP's problem.

> The thing you can't do is make a virtual call to a PURE VIRTUAL
> function in a destructor.

You shouldn't call a pure virtual anywhere :)

Back to the OP's problem: when cleanup activity is defined/refined
in subclasses, you cannot depend on it happening through the parent
destructor, since the destructor's type context never reaches into
the subtypes.

The behavior you want requires that certain points of behavior retain
their dyanmism beyond the start of the destruction phase, or that their
final specialization happens in the same class where you call them
in the destructor.

You can do that by messing around with the type system, and placing
instantiation barriers at various places, so that a destructor call
to disconnect() always hits the right place.  This is not simple,
nor good looking; you would have to make sure that disconnect()
[and similar points of specialization] do not get refined/redefined
in the subclasses (otherwise, we're back where we started).

Or, you can partition your classes, so that the connection object
is not embedded in the class under focus, and you can disconnect()
it through the appropriate mechanism before you destroy it; e.g.:
something like this:

     class MyClass {
        connection_type *cnxn;
     public:
        virtual ~MyClass() {
            cnxn->disconnect();
            delete cnxn;
            /// more destruction ...
        }
        /// etc ....
     };

-- 
A. Kanawati
NO.antounk.SPAM@comcast.net

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Antoun
1/13/2005 9:50:06 PM
Reply:

Similar Artilces:

calling virtual destructors and virtual functions
Say I have a class A, and a class B that inherits from A. Now A (and B) has a virtual destructor and a virtual function F(); If I now make these statements A* ptrA = new B; ptrA->F(); delete ptrA then in the statement ptrA->F(), by means of the polymorph behavior, the F() of class B is called. But the F() of class B only. And in delete ptrA, both destructors of class A and B are called. Is this right? Because then the two statements behave differently. Somehow, for a moment, I was thinking that in the call ptrA->F(), both virtual functions of class A and B should be processed. *...

how to call functions in C++ code from c
Hi there, Now I'm writing code mainly in C++. And some existing c code will call some functions which are in a C++ class. I read the basic techniques introduced from a SUN's web site. Basically 1. we can add extern "C" keyword, or 2. use the object in C++ code as struct in C. My question is: do we have to initialize the object in c? because there is no constructor in c, will it call a default constructor in c++ when we declare struct M; in c, M is an object defined in C++? Is there any detailed reference available on net? TIA Mike "Mike Qin" <lqin@sce.c...

How to call a C++ function from c code?
How to call a C++ function from c code? extern "C++"? I think it just inhibit the warning. I maybe have to consider c++ object creation problem. Does the C++ need to be a static function? BTW, the c code is compiled with C++ compiler. "AL@TW" wrote: > > How to call a C++ function from c code? > extern "C++"? No. In general, you can't, because of C++ overloading. You can call C from C++, however. -- [mail]: Chuck F (cbfalconer at maineline dot net) [page]: <http://cbfalconer.home.att.net> Try the download section. AL@T...

Calling C++ functions in C function through function pointers
Hi All!! I have a C++ program that uses callback funtions which are the private members of class. The code uses an API wrtiiten in C which supplies callback-setting functions that require pointers to these functions... The funtions wherein these API's callback-setting functions are called, are public members of the same class of which the callbacks are the private member. Now the API functions are generating compile errors since they cannot "understand" the C++ function pointers. Consider the sample code: class classname { public : /* Constructor for the class...

Calling C++ functions in C function through function pointers
Hi All!! I have a C++ program that uses callback funtions which are the private members of class. The code uses an API wrtiiten in C which supplies callback-setting functions that require pointers to these functions... The funtions wherein these API's callback-setting functions are called, are public members of the same class of which the callbacks are the private member. Now the API functions are generating compile errors since they cannot "understand" the C++ function pointers. Consider the sample code: class classname { public : /* Constructor for the class...

how to call a C++ function from a C file when provided with only compiled code
I have an existing C++ library . Now i am another application using this C++ lib. The problem here is i want to call C++ fn. from C file .I cannot use extern "C"declaration for that fn. because it is compiled using a g++. tobeused.cc writtenincpp(int i ,char c) { } Since i have been provided with .o's and the header files ,i can change only function prototypes and not function declaration. What should i do ? regards, ankit On 14 Sep 2006 22:08:07 -0700 in comp.lang.c++, "ankitjain.bvcoe@gmail.com" <ankitjain.bvcoe@gmail.com> wrote, >The problem here is i...

calling Matlab code from C/C++ code
Hi, I am learning to call Matlab code from C/C++ code. Here are my questions (1)are using Matlab engine and converting Matlab code into a C or C++ shared library the only two ways? (2) what's the difference between these two methods? Advantages and disadvantages? In what case use which method is better? Thanks and regards! On Mon, 03 Aug 2009 10:33:00 -0400, Tim <timlee126@yahoo.com> wrote: > Hi, > I am learning to call Matlab code from C/C++ code. Here are my > questions > > (1)are using Matlab engine and converting Matlab code into a C or C++ > shared library...

Destructor calling order from function calls different from <Effective C++>
Hey, In the book <Effective C++>, the author provides an example to prove why we need "pass by reference". I redoed the example, and found something interesting. The codes are: ############################## #include <iostream> class Student{ public: Student(){ std::cout << "inside CTOR. this = " << this << std::endl << std::endl; } Student(const Student& rhs){ std::cout << "inside COPY CTOR. this = " << this << ", rhs = "<< &rhs << std::endl <<...

calling c++ virtual functions
Hi everyone. I'm having trouble trying to call a c++ virtual function on a dll from Dolphin, and can't see what am i doing wrong. The function is beeing called, but what should be the first parameter, it's a 32bit constant value (i think it's not *this* pointer, though). i've tried changing the calling convention in both Dolphin and the dll, but didnt work ... any tips ? The example is pretty simple. this is my dolphin wrapper: ExternalStructure subclass: #IExperimenting IExperimenting>>inc: i "virtual int Inc(int i)" <virt...

Calling virtual functions from destructors?
Hi I've had a problem with gcc mac osx which I think I figured out. I would like to double check with people here to see if my understanding is correct: I have a class A which class B inherit from. A has a pure virtual function virtual in f1() = 0. In B I implement this function and the compiler works out the code. However from A's destructor B can be compiled and then the runtime aborts with saying that a call to a pure virtual function is not allowed. I'm assuming that B's destructor has been called before A's destructor and thus it won't allow me to call the...

calling virtual function from within another virtual function
Hi Guys, Is Ok to invoke a virutal function from within virtual function. Specifically here is the example I tried and it seems to have worked: (what I am doing is derived class::foo() (foo is virtual)invokes base case implementation of foo(), which in turn calls bar() thats virutal too . So I am reusing some part of logic which is common to both base and derived and overriding other part which is different by using 2 virtual functions like this) #include <iostream.h> using namespace std; class C { public: virtual void foo(int foo) { cout << "in C::foo() foo="...

Calling Lisp Function from C: How to declare this function in C land ?
Hi all: I have a lisp image that contains the following functions: (defun frgo (a) (format *debug-io* "~%~A~&" a) (values)) (cffi:defcallback frgo_helper :void ((a-cstr :string)) (frgo (cffi:foreign-string-to-lisp a-cstr))) In a C dynamic library I have: * file frgo_c.h: extern void frgo_helper( char * a ); * file frgo_c.c: void frgo( char * a ) { frgo_helper( a ); } Now, the library does not compile - undefined symbol _frgo_helper() ! How do I make functions "known" to C land that are purely defined as callbacks in Lisp lan...

calling virtual function results in calling function of base class ...
Hi, after browsing FAQ and archive for a while I decided that the following is a legal question. Consider this: Class Base { public: Base() {} Base(A* a, B* b); virtual A* foo(P* p, S& s); // using myA and myB protected: A* myA; B* myB; }; class Der : public Base { public: Der(O* o) : Base(), myO(o) {} A* foo(P* p; S& s); // not using myA and myB private: O* myO; }; class Bogus { public: Bogus(Base* b) : myBase(b) {} void bar() { ... myBase->foo(p,s); ... } private: Base* myBase; }; int main(/*args*/) { ... Der der(someO); Bogus* bogus = new Bogus(d...

PDA: How does the VI in the &quot;Calling External Code (Inline C Method)&quot; example link to the called functions?
The PDA module provides an example of calling external code via an inline C &nbsp; The inline source code from the example: &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; OSVERSIONINFO info; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); &nbsp;&nbsp;&nbsp;&nbsp; Err = GetVersionEx(&amp;info); &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; MajorVersion = info.dwMajorversion; &nbsp;&nbsp;&nbsp;&nbsp; MinorVersion = info.dwMinorversion; &nbsp; The PDA build specification includes *no* add...

Web resources about - Avoid virtual function when calling common code in destructor - comp.lang.c++.moderated

Varroa destructor - Wikipedia, the free encyclopedia
Varroa destructor is an external parasitic mite that attacks the honey bees Apis cerana and Apis mellifera . The disease caused by the mites ...

Microsoft – The New Destructor of Innovation?
If you read our blog from time to time, you'll know that Brad and I dislike the U.S. patent system with a particular distate for software patents. ...

Choose the form of your Ghostbusters donut destructor
Promising to make your stomach feel like the floor of a taxicab, Krispy Kreme has announced that it will celebrate the 30th anniversary of Ghostbusters ...

Mitt Romney, Uncreative Destructor by @DavidOAtkins
Mitt Romney, Uncreative Destructor by David Atkins Mitt Romney had a fascinating take on the foreclosure mess today. Dave Dayen has a superb ...

Crave 79: Choose the form of the Destructor
Empty your heads. Don't think of anything. Whatever happens, don't think of DARPA's talon-limbed Cheetah robot.

Destructors Considered Harmful
Allocating dynamic resources may seem hazardous but freeing them is the real hazard.

Transformers: Fall of Cybertron multiplayer faces Dinobot Destructor Pack next week
... robots will meet the eye in Transformers: Fall of Cybertron multiplayer next week. Game director Matt Tieger told Polygon that a "Dinobot Destructor ...

Varroa destructor mite mimics two types of bee
The parasitic bee mite Varroa destructor, which can mimic the chemical composition of its host's cuticle, is also capable of adapting this composition ...

Microsoft - The New Destructor of Innovation
The web's technology news site of record, Techmeme spotlights the hottest tech stories from all around the web on a single page.

Glenn Reynolds: Liberals have chosen The Donald as their 'Destructor'
Weak and ineffectual leadership created the vacuum Trump is filling. “Choose the form of the Destructor,” says the demon in Ghostbusters . Bill ...

Resources last updated: 1/24/2016 4:20:10 PM