Constructors
A constructor is a particular function for automatic initialization of an object. When an object is created, the special member function, which is the constructor will be executed automatically. The constructor function is various from all other non static member functions in a class since it is used to initialize the variables of whatever instance being created.
The Rules for writing constructors:
1. A constructor name has to be the similar as in which of its class name.
2. It is declared along with no return type
3. It cannot be declared const or volatile but constructor could be invoked for a const and volatile object
4. It might not be static
5. It might not be virtual
6. It should have public or protected access inside the class
The common form of constructor declaration is
Class user_name
{
private:
----------
----------
protected:
-----------
------------
public:
user_name( ); // constructor
------------
------------
};
user_name :: user_name( )
{
-------------
-------------
}
Example:
Class student
{
private:
char name[20];
int stcode;
char address[20];
public:
student ( ); // constructor
void get_data( );
void put_data( );
}
student :: student( ) //constructor
{
}
Constructors and destructors could be explicitly called. A constructor is automatically invoked whenever an object starts to live. The constructor called before main( ) begin for execution. The constructors could be invoked whenever a temporary object of a class requires to be created.