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.