C++ - constructor and destructors when they are called.
Home page C++ C++ Hardware HTML i javascript Java Software SQL

C++ - constructor and destructors when they are called.

Added: 2012-03-31

If you create an object, you need to know, when the program calls constructors and destructors. If you created a “statically” object (CClass cl;), that program will start automatically constructor, and when is ended code block, automatically destructor will be run.

In case when is creating pointer (CClass* cl;) to object, if it is not initialized, constructor will not be running and destructor.

After initializing the variable that is a pointer (CClass* cl = new CClass();), will be running constructor. When is ended using pointer, programmer must run destructor (cl->~CClass();) or run delete command (delete cl;).

In case when a class inherits from another, constructor will be run, starting from the oldest parent, to the youngest children. Example, if class CClass (children) inherit form class CClass2 (parent), then first be run constructor CClass2 (CClass2::CClass2();) after then CClass (CClass::CClass();). When the destructor is called, order will be inverse, first be running destructor children after parent (CClass::~CClass(); CClass2::~CClass2();).