By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,407 Members | 1,033 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,407 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Share this Question
Share on Google+
7 Replies


P: n/a
* 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

P: n/a
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

P: n/a
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_back( 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

P: n/a
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

P: n/a

"eric" <er*********@gmail.comwrote in message
news:11**********************@l12g2000cwl.googlegr oups.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

P: n/a
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

P: n/a
>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 discussion thread is closed

Replies have been disabled for this discussion.