What are Constructors and Destructors?

Tue Jul 03, 2007 11:41 pm

What are Constructors and Destroyers(Destructors) and how it is used in C++?
----------------------------------------------------------------


Constructors from a conceptual level enable the creation of an object of a given class- a constructor is a method of a class with no return parameters. Constructors also enable the initialization of any variables of a class; you can supply input parameters to constructors. Constructors can have access modifiers- Private, Protected and Public.

A constructor gets called automatically when you create an object of a class; if you don't define your own constructor, by default a constructor is called which is the "Default Constructor". A class can have more than one constructor. It has the same name as the class itself.

Destructors are again methods of a class that enable the destruction of an object after its use; destructors also provide the means of memory clean up after usage. Destructors are always called in the reverse order of Constructors. There can only be one destructor per class and they neither take an input parameter nor do they return anything. Destructors need not be called explicitly.

cpp code
class Vehicle
{
Int Registration = 0;
public:
Vehicle(int regis) // constructor
{
Registration = regis;
}
Virtual void GetRegistration() = 0;
~Vehicle() // destructor
{
// Set things to null and free memory
}
};




  Related Posts  to : What are Constructors and Destructors?
 Class constructors     -  

Topic Tags

C++ OOP