C++:: Constructors and Destructors


Constructors in C++ are special member functions of a class. A Constructor is a function that initilizes the members of object.There can be any number of overloaded constructors inside a class.The Constructor is automatically called whenever an object is created or dynamically allocated using "new" operator.

If no constructor is supplied then a default one is created by the compiler without any parameters.If you supply a constructor with parameters then default will NOT be created.

Some Points about Constructor:

-- Constructors have the same name as the class.
-- Constructors do not return any values.
-- Constructors are invoked first when a class is initialized. Any initializations for the class members,memory allocations are done at the constructor.
-- Constructors are never virtual.


Class Sample{

Sample(){ ..}


Destructors in C++ also have the same name,except that they are preceded by a '~' operator. The destructors are called when the object of a class goes out of scope.The main use of destructors is to release dynamic allocated memory.Destructors are used to free memory,release resources and to perform other cleanup.If the destructor is not declared inside a class,the compiler automatically create a default one.

If the constructor/destructor is declared as private,then the class cannot be instantiated.



No comments:

Post a Comment