首页 > 代码库 > Constructor and destructor -- Initialization & Cleanup in C++

Constructor and destructor -- Initialization & Cleanup in C++

Why need initialization and cleanup?

A large segment of C bugs occur when the programmer forgets to initialize or clean up a variable.

The class designer can guarantee initialization of every object by providing a special function called the constructor. If a class has a constructor, the compiler automatically calls that constructor at the point an object is created, before client programmers can get their hands on the object. The constrctor call isnot even an option for the client programmer, it is performed by the compiler at the point the object is defined.

 

Default constructors 

a default constructor is ont that can be called with no arguments. A default constructor is used to create a "vanilla object". The default constructor is so important that if and only if there are no constructors for a structure(struct or class), the compiler will automatically create one for you.

For example

class V{

  int i;

};

void main()

{

  V v, v2[10];

}

It is OK.

But if any constructors are defined, however, and there‘s no default constructor, the instances of V above will generate compile-time errors.