6: Initialization and Cleanup

1.constructor

In C++, the class designer can guarantee initialization of every object by providing a special function called the constructor whose name is the same as class's name.

class A
{
private:
	int a;
public:
	A();
};



int main()
{
	A ta;
}
In this simple example, storage is allocated for the object. And the compiler quietly inserts the call to A::A() for the object a at the point of definition. Like any member function, the first(secret) argument to the constructor is the this pointer - the address of the object for which it is being called.

Notice: If you have a constructor, the compiler ensures that construction always happend. If there are no constructors for a class, the compiler will automatically create one for you.

2.destructor

The destructor never has any arguments because destruction never needs any options.

3.no return value

Both the constructor and destructor are very unusual types of functions: they have no return value. This is distinctly diffenent from a void return value, in which the function returns nothing but you still have the option to make it something else.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章