|
C++ is a wonderful language. I could hardly be a bigger fan of inheritance, polymorphism, template and many of the other features of C++.
But all things come at a price and one of those prices tends to be program bloat.
Consider:
class Three{ long m_test; public: Three(void); virtual ~Three(void);
};
class One{ public: Three m_three; One(void); virtual ~One(void);
};
class Two :public One{ public: Two(void); virtual ~Two(void); };
class Three { long m_test; public: Three(void); virtual ~Three(void); };
Any instance of class Two will be 12 bytes long, e.g. 4 bytes for the "long" in class Three and 4 bytes each for the virtual function tables for class Three and One and Two.
This is not intended to be a course on C++ but let us remind ourselves of the purpose of the virtual destructor.
If we use polymorphism and have: Two *pTwo = new Two(); One *pOne = pTwo; delete pOne; then without the virtual destructor, the destructor code for class Two will never be called. With resulting memory leaks if class Two allocates any memory.
But here we have two "ifs", if we are using polymorphism and if class Two does allocate any memory. Meanwhile our class uses 8 bytes more memory than it needs to for every instance we allocate.
It is notable, that Microsoft Visual C++ 6.0 makes virtual destructors the default, even for generic classes, In Microsoft Visual C++ 7.00 they have to be selected as an option when you use the class wizard to create a new class.
|