473,748 Members | 2,496 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

confused by virtual destructor example in "effective c++"

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
...
private:
std::string name;
std::string address;
};

i don't understand why the destructor is virtual. the comment refers
to item 7, a discussion on virtual destructors which summarizes itself
like so: "declare a virtual destructor in a class if and only if that
class contains at least one virtual function."

class Person has no virtual function (other than the destructor). the
class body contains a "..." to indicate other unspecified code, so
perhaps the reader is meant to infer that the "..." includes one or
more virtual member functions, but that's not consistent with the usage
given for the class:

the text goes on to show a class Student which inherits from Person.
like Person, Student has only one virtual function, the destructor.
(the body of Student also contains a "...").

if this class hierarchy is polymorphic - i.e. if the "..."s indicate
one or more virtual member functions - then i'd expect to see usage
like this:

Person *student = new Student();
...
delete student;

item 7 explains that in this case the delete would lead to undefined
behavior unless the destructor is virtual.

but the class isn't used like that, it's used like this:

bool validateStudent (const Student& s);
Student plato;
bool platoIsOK = validateStudent (plato);

there's no polymorphism there, and nothing to indicate the need for a
virtual destructor.

item 7, cited in the comment to explain the need for a virtual
destructor, seems to me to indicate the opposite: "some classes are
designed to be used as base classes, yet are not designed to be used
polymorphically . such classes are not designed to allow the
manipulation of derived class objects via base class interfaces. as a
result, they don't need virtual destructors."

what am i missing?

TIA
eric

Dec 4 '06 #1
7 3089
* eric:
>
what am i missing?
That the class /can/ be used polymorphically . It's designed for
polymorphism. Even if it isn't used that way in the concrete example.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 4 '06 #2
i don't understand why the destructor is virtual. the comment refers
to item 7, a discussion on virtual destructors which summarizes itself
like so: "declare a virtual destructor in a class if and only if that
class contains at least one virtual function."
I think it would be better if example contains at least one
(pure)Virtual function.

>
class Person has no virtual function (other than the destructor). the
class body contains a "..." to indicate other unspecified code, so
perhaps the reader is meant to infer that the "..." includes one or
more virtual member functions, but that's not consistent with the usage
given for the class:
item 7, cited in the comment to explain the need for a virtual
destructor, seems to me to indicate the opposite: "some classes are
designed to be used as base classes, yet are not designed to be used
polymorphically . such classes are not designed to allow the
manipulation of derived class objects via base class interfaces. as a
result, they don't need virtual destructors."
If this is the case then Base class would not have any virtual (or pure
virtual) function, .
And as mentioned in the book "Virtual Destructor only need when atleast
one virtual is there"
what am i missing?

--raxit sheth

Dec 4 '06 #3
eric wrote:
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
...
private:
std::string name;
std::string address;
};

i don't understand why the destructor is virtual. the comment refers
to item 7, a discussion on virtual destructors which summarizes itself
like so: "declare a virtual destructor in a class if and only if that
class contains at least one virtual function."
The goal of writing a base class is to design an interface that allows
a derivative class to participate in a system or construct. What he is
doing here is bypassing the details of what exactly you'ld need in a
base class like Person. Let say that you plan to use this base class to
store Students, Seniors, Part-Time Students and Sophomores. You'll
probably need to have all those derivatives support a virtual method to
get their marks / scores. Something like getScore() or getAverage().
Whatever method you choose you'ld probably declare it pure virtual:

class Person {
std::string name;
std::string address;
public:
Person();
virtual ~Person(); // see item 7 for why this is virtual
virtual getAverage() const = 0; // to be implemented in the
derivatives
};

And that makes sense since Person is abstract (just like a Shape or
Vehicle is abstract). If you derive from Person and write a Student
class but fail to implement getAverage(), the compiler will bark back
at you.
The whole point to making that abstract class is that your code can use
the abstract interface and let the same code work with any derivative.
Including a derivative you haven't written yet.

Example:

std::vector< Person* people;

can hold any kind of Person.

people.push_bac k( new Student("Santa Claus","North Pole") );
for( size_t i = 0; i < people.size(); ++i)
{
people[i]->getAverage() ; // is guarenteed to be available
}
....
>
class Person has no virtual function (other than the destructor). the
class body contains a "..." to indicate other unspecified code, so
perhaps the reader is meant to infer that the "..." includes one or
more virtual member functions, but that's not consistent with the usage
given for the class:
Don't you think it would be harmfull if he starts getting into the
specifics of what a virtual function's purpose might be. He's letting
you use your imagination. A virtual function could be returning a grade
level, the program the student is in, his/her major/minor, couses
enrolled in, sex. etc...
>
the text goes on to show a class Student which inherits from Person.
like Person, Student has only one virtual function, the destructor.
(the body of Student also contains a "...").
The student has, by obligation, any virtual function defined in Person
and then some.
>
if this class hierarchy is polymorphic - i.e. if the "..."s indicate
one or more virtual member functions - then i'd expect to see usage
like this:

Person *student = new Student();
...
delete student;

item 7 explains that in this case the delete would lead to undefined
behavior unless the destructor is virtual.
Yes it would. the variable student is a pointer to Person. the variable
itself could have been called anything. Its name is irrelevant. Its a
base class pointer to a Derived object. Since you've newed it, you
eventually have to delete it.
>
but the class isn't used like that, it's used like this:

bool validateStudent (const Student& s);
Student plato;
bool platoIsOK = validateStudent (plato);
You are reading an item here that refers to preferring pass_by_ref
versus pass_by_value.
Thats not item 7, its Item 20 i beleive.
Again, don't get dug into the specifics. If validateStudent () is not a
requirement of a Student hierarchy using a Person base class, it
wouldn't make sense to have the entire hierarchy support a virtual bool
validateStudent (const Person& r_p). Hence, passing Student& by
reference makes logical sense.
>
there's no polymorphism there, and nothing to indicate the need for a
virtual destructor.
Yes there is. A copy_by_value has a cost that involves more than just
copying a student. Student plato also has a Person base with a
std::string name and address. A Student *copy* would therefore involve
at least 4 copy constructors in this case. Thats also clearly explained
in his text.
Polymorphism isn't only about allocations.
>
item 7, cited in the comment to explain the need for a virtual
destructor, seems to me to indicate the opposite: "some classes are
designed to be used as base classes, yet are not designed to be used
polymorphically . such classes are not designed to allow the
manipulation of derived class objects via base class interfaces. as a
result, they don't need virtual destructors."

what am i missing?
The last point is an important one. Determining *when* a virtual d~tor
is required is just as important as determining when one is not needed.
He cites as an example a Point class which is targetted for
composition. Don't declare a virtual d~tor if you don't plan to derive
from Point to satisfy the system / construct.
Its not neccessarily about the *cost* of a virtual d~tor he is
referring to. As he states - it makes your intentions clear to the
coder who scans your code.
"This class is not intended to be derived from".

This book is not about the details and basics of C++ code. As clearly
stated in the introduction. Its about the relationship between the
creator of classes and the user of those classes. You need at least a
little experience from both sides of the coin to benefit from that text.

Dec 4 '06 #4
hello,

On Dec 4, 1:15 pm, "Salt_Peter " <pj_h...@yahoo. comwrote:
store Students, Seniors, Part-Time Students and Sophomores. You'll
probably need to have all those derivatives support a virtual method to
get their marks / scores. Something like getScore() or getAverage().
obviously if you come back to the Person class and add a virtual member
function, then the class needs a virtual destructor. as implemented in
the book, the Person class doesn't have any virtual member functions.
class Person has no virtual function (other than the destructor). the
class body contains a "..." to indicate other unspecified code, so
perhaps the reader is meant to infer that the "..." includes one or
more virtual member functions, but that's not consistent with the usage
given for the class:
Don't you think it would be harmfull if he starts getting into the
specifics of what a virtual function's purpose might be.
i'm not suggesting that the book should get into any specifics about
the purpose of a virtual function. my point is that there's not even
the indication of the existence of a virtual function.
if this class hierarchy is polymorphic - i.e. if the "..."s indicate
one or more virtual member functions - then i'd expect to see usage
like this:
Person *student = new Student();
...
delete student;
item 7 explains that in this case the delete would lead to undefined
behavior unless the destructor is virtual.
Yes it would. the variable student is a pointer to Person. the variable
itself could have been called anything. Its name is irrelevant.
i attach no significance to the variable name. substitute "x" for
"student". my point is that you would need usage such as that above to
indicate the need for polymorphism, and no such usage is suggested.
but the class isn't used like that, it's used like this:
bool validateStudent (const Student& s);
Student plato;
bool platoIsOK = validateStudent (plato);
You are reading an item here that refers to preferring pass_by_ref
versus pass_by_value.
Thats not item 7, its Item 20 i beleive.
the implementation and example usage of class Person appears in item
20, to illustrate the case for pass-by-reference-to-const instead of
pass-by-value. the gist of item 20 doesn't concern me, the point is
that item 20 refers to item 7 to explain why ~Person() is virtual, but
with the given implementation and usage of the Person class, item 7
would call for ~Person() to be not virtual.
Again, don't get dug into the specifics. If validateStudent () is not a
requirement of a Student hierarchy using a Person base class, it
wouldn't make sense to have the entire hierarchy support a virtual bool
validateStudent (const Person& r_p). Hence, passing Student& by
reference makes logical sense.
? validateStudent () can't be virtual, only member functions can be
virtual. anyway i'm OK with the arguments made in item 20.
there's no polymorphism there, and nothing to indicate the need for a
virtual destructor.
Yes there is. A copy_by_value has a cost that involves more than just
copying a student. Student plato also has a Person base with a
std::string name and address. A Student *copy* would therefore involve
at least 4 copy constructors in this case.
the book specifies that the cost of passing Student by value is six
constructors and six destructors. but this is true regardless of
whether or not the Person/Student hierarchy supports polymorphism. the
points made in item 20 are equally valid whether or not ~Person() is
virtual.
The last point is an important one. Determining *when* a virtual d~tor
is required is just as important as determining when one is not needed.
He cites as an example a Point class which is targetted for
composition. Don't declare a virtual d~tor if you don't plan to derive
from Point to satisfy the system / construct.
Its not neccessarily about the *cost* of a virtual d~tor he is
referring to. As he states - it makes your intentions clear to the
coder who scans your code.
"This class is not intended to be derived from".
by not providing a virtual destructor, you're not saying "don't derive
from this class", you're saying "this class isn't polymorphic." there
are uses for inheritance in the absence of polymorphism.

regards,
eric

Dec 4 '06 #5

"eric" <er*********@gm ail.comwrote in message
news:11******** **************@ l12g2000cwl.goo glegroups.com.. .
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
...
private:
std::string name;
std::string address;
};

i don't understand why the destructor is virtual. the comment refers
to item 7, a discussion on virtual destructors which summarizes itself
like so: "declare a virtual destructor in a class if and only if that
class contains at least one virtual function."
Personally, I use a different rule: If the class is intended as a base
class, then I make the destructor virtual. The "if and only if" rule above
seems a little restrictive to me.
class Person has no virtual function (other than the destructor). the
class body contains a "..." to indicate other unspecified code, so
perhaps the reader is meant to infer that the "..." includes one or
more virtual member functions, but that's not consistent with the usage
given for the class:

the text goes on to show a class Student which inherits from Person.
like Person, Student has only one virtual function, the destructor.
(the body of Student also contains a "...").

if this class hierarchy is polymorphic - i.e. if the "..."s indicate
one or more virtual member functions - then i'd expect to see usage
like this:

Person *student = new Student();
...
delete student;

item 7 explains that in this case the delete would lead to undefined
behavior unless the destructor is virtual.

but the class isn't used like that, it's used like this:

bool validateStudent (const Student& s);
Student plato;
bool platoIsOK = validateStudent (plato);

there's no polymorphism there, and nothing to indicate the need for a
virtual destructor.
Well, there is the _possibility_ of polymorphism here. Since
validateStudent takes a reference to a Student, it's perfectly legal to pass
an instance of a class derived from student. The example doesn't show it,
but it's not prohibited in any way.
>
item 7, cited in the comment to explain the need for a virtual
destructor, seems to me to indicate the opposite: "some classes are
designed to be used as base classes, yet are not designed to be used
polymorphically . such classes are not designed to allow the
manipulation of derived class objects via base class interfaces. as a
result, they don't need virtual destructors."

what am i missing?
Perhaps the example was simplified from its original form, and at some point
lost a virtual member function it once had (in that ... section)? Perhaps
originally it was followed up with an example of actual polymorphic use?
Perhaps it is expanded on later in the book with an example which _does_ use
the class polymorphically ? Or perhaps he didn't follow his own rule this
time?

Who knows? Perhaps you could ask Mr. Meyers?

(In the second edition, he points out that you can still get bitten by not
having a virtual destructor even though you had no virtual function which
would trigger the rule. He also states that "many people" use that rule,
and discusses the reasons for it and problems with following or not
following it. So I would guess he is not (or _was_ not) a strict follower
of that if-and-only-if rule himself.)

But you seem to understand the concepts ok. I'd ignore the apparent
inconsistency, and move on.

-Howard

Dec 4 '06 #6
eric wrote:
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
...
private:
std::string name;
std::string address;
};

i don't understand why the destructor is virtual. the comment refers
to item 7, a discussion on virtual destructors which summarizes itself
like so: "declare a virtual destructor in a class if and only if that
class contains at least one virtual function."
This is not strictly true. if you have 0 virtual functions and you
delete a pointer to a base class you will not call the destructor of
the derived class and thus you could have a memory leak.

Just becase there are 0 virtual functions does not mean someone will
not store pointers to base classes and try to delete them.

Therefore good practice is to make your destructor virtual if it is
possible someone could derive from your class in the future, regardless
of whether virtual functions exist.

See example, below. There are no virtual functions but there is a
memory leak and is bad coding.

#include <iostream>

struct base
{
base() {}
};

struct derived : public base
{
derived()
{
i = new int[500];
}
~derived()
{
std::cout << "~derived" << std::endl;
delete [] i;
}

int* i;
};

int main(int argc, char** argv)
{
derived* d = new derived;

base* b = d;

delete b;

return 0;
}

--
Ivan
http://www.0x4849.net

Dec 5 '06 #7
>Ivan Novick wrote:
This is not strictly true. if you have 0 virtual functions and you
delete a pointer to a base class you will not call the destructor of
the derived class and thus you could have a memory leak.
It could be worse than that. Formally, the behavior of a program is
undefined.
Just becase there are 0 virtual functions does not mean someone will
not store pointers to base classes and try to delete them.

Therefore good practice is to make your destructor virtual if it is
possible someone could derive from your class in the future, regardless
of whether virtual functions exist.
It's good practice to design you class according to what it's supposed
to do, document your design. You cannot solve problems that other
programmers cause themselves by not reading documentation. Make your
destructor virtual if your design calls for deleting objects of derived
types through pointers to your base class.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Dec 5 '06 #8

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

Similar topics

12
13465
by: cppaddict | last post by:
Hi, I know that it is illegal in C++ to have a static pure virtual method, but it seems something like this would be useful when the following 2 conditions hold: 1. You know that every one of your Derived classes will need to implement some method, but implement it differently, and that the base class cannot implement it. This is where pure virtual comes in.
175
8875
by: Ken Brady | last post by:
I'm on a team building some class libraries to be used by many other projects. Some members of our team insist that "All public methods should be virtual" just in case "anything needs to be changed". This is very much against my instincts. Can anyone offer some solid design guidelines for me? Thanks in advance....
5
3342
by: Frederick Gotham | last post by:
If we have a simple class such as follows: #include <string> struct MyStruct { std::string member; MyStruct(unsigned const i) {
8
2056
by: gw7rib | last post by:
I've been bitten twice now by the same bug, and so I thought I would draw it to people's attention to try to save others the problems I've had. The bug arises when you copy code from a destructor to use elsewhere. For example, suppose you have a class Note. This class stores some text, as a linked list of lines of text. The destructor runs as follows: Note::~Note() {
0
8831
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
9376
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...
1
9329
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6076
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
4607
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
3315
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
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.