Key points:
If a base class or class with polymorphism has a virtual function, the Destructor should be declared as virtual. For example
Class TimeKeeper {public: TimeKeeper ();~ TimeKeeper () ;}; class AtomicClck: public TimeKeeper // atomic clock {}; class WaterClck: public TimeKeeper // water clock {}; class WristClck: public TimeKeeper // watch {}; int main () {TimeKeeper * ptk = getTimeKeeper (); // The delete ptk object for getting the clock using the factory method; // because the Destructor declaration in the parent class is non-virtual, therefore, only the destructor of the parent class will be executed. // This will cause memory leakage of special members in the subclass}
The code above causes memory leakage and does not release the memory occupied by a part of the subclass. The solution is to add virtual before the destructor of the parent class, as shown below:
class TimeKeeper{public: TimeKeeper(); virtual ~TimeKeeper();};
Key points: class memory
(1) Internal member variables:
- Common variables: Memory usage, but the alignment principle should be noted (similar to struct type ).
- Static modified static variables: NO content is occupied because the compiler places it in the global variable area.
(2) Internal member functions:
- Common functions: Does not occupy memory.
- Virtual Functions: Takes 4 bytes to specify the entry address of the virtual function table of the virtual function. Therefore, the addresses occupied by the virtual functions of a class are unchanged, and there is no relationship with the number of virtual functions.
PS: even if there is nothing in the class, it must take up one byte.