Re: virtual fn, destructor
On Dec 14, 2:40 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
Martin Drautzburg wrote:
[...]
Practical example: Suppose you have a class named "Pixel",
which contains four unsigned char members: red, green, blue
and alpha. As it is, one instantiation of this class will
require 4 bytes of memory. If you, for example, represent an
image as a std::vector<Pixel>, the memory consumption will be
the amount of pixels times 4 bytes.
However, if you go and needlessly make the destructor of
"Pixel" virtual, the memory consumption will double (or triple
if you are compiling to a 64-bit system, where pointers are 8
bytes large).
Quadruple, in fact, on most systems, because of alignment
considerations. Drop the alpha component, and I have
sizeof(Pixel) == 3 with no virtual functions; sizeof(Pixel) ==
16 with a virtual destructor.
It is quite unlikely that you will ever inherit anything from
"Pixel" (especially if your basic datatype is
std::vector<Pixel>, which does not in itself support
specialization of the elements), so making any function
virtual would only be a waste of memory.
It's a value type. It supports assignment. We all know that
polymorphism and assignment don't mix. Declaring anything
virtual in a value (including the destructor) is probably a sign
of poor design: is it a value, or isn't it? Even the author
doesn't know.
For me, this is an even more important issue than the size
(although for things like Pixel, size does matter).
Another price to pay is that calling a virtual function is
slightly slower than calling a non-virtual one. This might not
be relevant in most cases, but with small functions which get
called millions of times per second, it might make a
difference.
Get a compiler with a better optimizer:-). (Good compilers can
solve this one.)
So I keep thinking: why not just make *every* function and
*every* destructor virtual (and rename "virtual" to
"natural"), if that relieves the headaches.
Because it causes overhead, especially with very small classes.
I wonder what is the reason for this "virtual" complexity.
Because the design principle of the C++ language is "you don't
pay for what you don't use".
Because independently of C++, a good design concept is "say what
you mean, and mean what you say". In C++, a virtual destructor
is generally understood as saying "derive from me". If that's
what you want to say, fine, but then you should probably also
ensure that there is no public assignment operator (and that if
copy is supported, it is via a virtual clone function, and not
just a public copy constructor).
The size issue is relevant for some classes---your example of
Pixel is a good one. But the design issue is relevant for all
classes.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34