Home | » | C++ Programming | » | Constructors |
The accessing of various members/objects of the class comparison of class with structures and use of classes using special member function called Constructors and Destructors for initializing and disposing of objects belonging to that class.
Contents
There are two ways to define an integer variable. You can define the variable and then assign a value later in the program.
for example
int height; //define a variable
------------- //other code here
height = 6; //assign it a value
or the second ways is, you can define the inter and immediately initialize it.
for example
int height = 6; //define and assign it a value
Initialization combines the definition of the variables with its initial assignment. Nothing stops you from changing that value later. Initialization ensures that your variable is never without a meaningful value.
But, how can you initialize the member data of a class? The answer is using constructors. Constructors are the special member function used for automatic initialization of the objects of the class. The Constructors are defined along with other member function. But the format of constructors definition is different from other member function. The Constructors can take parameters in their parenthesis as needed, but they cannot have return value not even void. The name of the constructors is same as that of class name. The Constructors are called in program automatically whenever an object of the class is created.
Characteristics of Constructor
- A constructor has the same name as that of the class
- A constructor is declared in the public section of a class.
- A constructor does not return any value, so return type is not associated with its definition.
- A constructor is invoked automatically as soon as the class object is created.
- A constructor can be overloaded and are not inherited.
Default Constructors
A Constructor with no parameters is called a default Constructor. It is used for initializing the object of a class. In other words, a default Constructor initializes the data members with no arguments. The default Constructor may be given by the programmer or if in case, you declare no Constructors at all. The compiler will automatically create a default constructor in for you. The default Constructor in the compiler provided no action, it is as if you had declared a constructors that took no parameters and whose body is empty. Following program illustrate default constructor.