473,657 Members | 2,521 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to define a virtual destructor

16 New Member
Hello people,
I know that in a base class you should define the destructor as virtual but is there any cases that you define a destructor as virtual. In the case when you implement assignment operator and copy constructor you need to implement the destructor as well but does it need to be virtual too or not?

many thanks
Sep 13 '07 #1
16 3073
Savage
1,764 Recognized Expert Top Contributor
Hello people,
I know that in a base class you should define the destructor as virtual but is there any cases that you define a destructor as virtual. In the case when you implement assignment operator and copy constructor you need to implement the destructor as well but does it need to be virtual too or not?

many thanks

I really don't understand what are you trying to say.

Could you please rephrase somehow?

Savage
Sep 13 '07 #2
jeff_rowa
16 New Member
I really don't understand what are you trying to say.

Could you please rephrase somehow?

Savage
well what I'm saying basically is when do you define a destructor as virtual besides in inheritance and for the base class.
Sep 13 '07 #3
RRick
463 Recognized Expert Contributor
Whew! Destructors and copy methods! While this is an innocent question, you have really opened up a big C++ can of worms.

First of all, the destructor, copy constructor and operator= are known as the "Big 3" methods and many times are grouped together. Some sources say that if you implement one of them, you should implement all of them. In this case, disabling a method by making it private counts as an implementation.

Notice that the above discussion makes no mention of the destructor being virtual. You must make the destructor virtual, if you have any plans to derive from this class. If you don't, you can introduce a bug due to "splicing". Does this mean the base class also has to define the copy methods, too? Only if the desctructor is releasing resources. I believe this is one of the few exceptions to the Big 3 rule.

The operator= can be made virtual (I think) but I haven't seen an example for doing this. Most cases for using operator= is between the same class. I believe operator= can be used to copy between base and derived classes (but I wouldn't bet the house on it). To me, this sounds like a diaster.

One last point on copying. There is a real need to make copies of derived objects from base class pointers. In this case, a technique called cloning is used where a virtual clone method is created.
Sep 13 '07 #4
Savage
1,764 Recognized Expert Top Contributor
well what I'm saying basically is when do you define a destructor as virtual besides in inheritance and for the base class.
It's good to have always a virtual destructor,you might need to derive from that class in a future to avoid reinventing the wheel,so whenever you can make it virtual unless your primary goal is speed.

Savage
Sep 13 '07 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
All of the above answers are incorrect.

A virtual destructor has nothing to do with the "Big 3" or the assignment operator.

You have to understand that only the compiler can create and destroy objects. As a courtesy, on creation the compiler will call a constructor so you can intialize any class members that haven't alreay been initialized. On destruction, a courtesy call to your destructor allows you to release any resources you may have allocated or to do any last minute work as the result of the object being destroyed.

Where a hierarchy is involved with a base class having virtual functions, the intent is to use base class pointers and references with derived objects. So, when you delete a base class pointer or reference, the base class destructor is called. And that's all.

If you you want your derived class destrutctor called, then the base class destructor must be virtual. In this case, the derived class destructor is called followed by a call to the base class destrcutor.

The rule is: If your base class has virtual functions, then it must have a virtual destrcutor. Otherwise, it's a design error.

A base class with no virtual functions and a virtual destrcutor is likewise a design error.
Sep 24 '07 #6
RRick
463 Recognized Expert Contributor
Actually, all of the above answers are correct; at least within their posts.

Savage took a safe path and suggested that all objects should have virtual destructors. This would stop the base class design flaw W4cats mentioned.

I personally don't care for this approach, but then I usually have access to the base class code, and can fix the above mentioned design flaw by modifying the destructor directly. If I can't access the original code, then I can wrap my own class around the offending object and hide its bad design with protected inheritence.

It might be my old C style coding habits, but I don't like making a class virtual ( and creating a virtual lookup table) unless it is really needed.
Sep 25 '07 #7
weaknessforcats
9,208 Recognized Expert Moderator Expert
It might be my old C style coding habits, but I don't like making a class virtual ( and creating a virtual lookup table) unless it is really needed.
Actually, this is exactly what you want. The base class object is really part of the derived object. When you call a base class private virtual method using a base class pointer, you want the call to be to the derived class override.

That means in object-oriented programming you base class will always need a vtbl.

Check out separating the interface from the implementation by reading up on the desing pattern Template Method.

I say again, a class with virtual functions and no virtual destructor is a design error.
Sep 25 '07 #8
Savage
1,764 Recognized Expert Top Contributor
Actually, this is exactly what you want. The base class object is really part of the derived object. When you call a base class private virtual method using a base class pointer, you want the call to be to the derived class override.

That means in object-oriented programming you base class will always need a vtbl.

Check out separating the interface from the implementation by reading up on the desing pattern Template Method.

I say again, a class with virtual functions and no virtual destructor is a design error.
Then why you said that my statement is incorrect?

I did said that it's good to always have a vdestructor,exc ept when your goal is speed.

Savage
Sep 25 '07 #9
weaknessforcats
9,208 Recognized Expert Moderator Expert
Then why you said that my statement is incorrect?

I did said that it's good to always have a vdestructor,exc ept when your goal is speed.
Sorry. I was referring to RRick's post #7.

Your statement of having virtual destructors for no reason on the off chance you will derive from the class in the future does not hold water. The reason is that this is a concrete class. That is, a class from which objects can be created.

When you derive from a concrete class, you cannot override base class methods since they aren't virtual. Your derived methods will just hide the base methods and remove that functionality from your derived class. That forces code like:
Expand|Select|Wrap|Line Numbers
  1. void Derived::AMethod(int arg)
  2. {
  3.        //Derived code goes here???
  4.        Base::AMethod();    //recover base class functionality
  5.        //Or does it go here???
  6. }
  7.  
Unfortuntately, now you can't tell whether the Base method call is a pre-condtion or a post-condition in the derived class and therefore have introduced ambiguity.

So the rule is: Never derive from a concrete class.

When you do derive, the base class will have virtual methods and that requires the virtual destructor.
Sep 26 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

11
10509
by: Stub | last post by:
Please answer my questions below - thanks! 1. Why "Derived constructor" is called but "Derived destructor" not in Case 1 since object B is new'ed from Derived class? 2. Why "Derived destructor" is called in Case 2 since only ~base() becomes "virtual" and ~Derived() is still non-virtual? 3. Does Case 3 show that we don't need any virtual destructor to make ~Derived() called? 4. Is "virtual destructor" needed only for Case 2?
37
4155
by: WittyGuy | last post by:
Hi, I wonder the necessity of constructor and destructor in a Abstract Class? Is it really needed? ? Wg http://www.gotw.ca/resources/clcm.htm for info about ]
26
3970
by: pmizzi | last post by:
When i compile my program with the -ansi -Wall -pedantic flags, i get this warning: `class vechile' has virtual functions but non-virtual destructor, and the same with my sub-classes. But when i add a virtual destructor like this : " virtual ~vechile". I get this error: Undefined first referenced symbol in file vtable for vechile /var/tmp//ccC9yD6Z.o
8
2574
by: Pete C | last post by:
In this section of the FAQ: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.10 an abstract destructor is given a definition with the cryptic comment "It's faster this way, trust me". Why? Is it faster to type? I notice that the derived classes in that example seem mysteriously not to require a destructor.
22
2390
by: ypjofficial | last post by:
Hello All, I have following doubt.. class abstractclass { public: abstractclass(){} virtual void method()=0; };
5
11348
by: druberego | last post by:
I read google and tried to find the solution myself. YES I do know that you can get undefined references if you: a) forget to implement the code for a prototype/header file item, or b) you forget to pass all the necessary object files to the linker. Neither of those are my problem. Please bear with me as the question I ask is rather long and I think it's beyond a CS101 level of linker stupidity. If it is a stupid CS101 mistake I'm making...
7
3082
by: eric | last post by:
hello i'm confused by an example in the book "Effective C++ Third Edition" and would be grateful for some help. here's the code: class Person { public: Person(); virtual ~Person(); // see item 7 for why this is virtual ...
8
2327
by: Shraddha | last post by:
What is the use of "PURE vitual distructors"? And why we can not have vitual constructors?
8
1834
by: lmfmaw | last post by:
Hi all, I've hit the wall with this "fairly" simple problem. As you can see in the code below, my destructors don't do their job as they are supposed to (I left them empty for this example). I'm running the Visual Leak Detector library (on VS 2005) to detect memory leaks and whatever I've tried it still complains.. Please can someone help me clean up properly? --------
0
8392
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
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8726
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...
0
8603
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7320
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
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
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
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
1944
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.