Home » Learn C++ » Constructors in C++

Constructors in C++

Constructors in C++:

            A constructor is a member function of a class that is called and executed automatically when an object of that class is created. The name of the constructor function is the same as the name of the class itself.
A constructor function may have arguments but it cannot return any value.

 

Program:

 

# include <iostream.h>
class test
{
public:
test ( )
{cout << “Welcome” << endl;}
abc ( )

{cout << “Ok” <<  endl;}
main
( )
{
test a, b, c;
}

Output of program
Welcome
Welcome
Welcome

 

            In the above program, the class “test” contains member function test”. This member function is the constructor function because name of this function and the name of the class are same. When the member function “test” is executed, it prints “Welcome” on the computer screen.

            In the program, three objects (a, b & c) of the class “test” are created. Each time an object of the class “test” is created, the constructor is executed and the word “Welcome” is printed on the computer screen. Since three objects are created, the word Welcome is printed three times.

 

Initialization Data Using Constructors:

            The constructor functions arc normally used to initialize values in data members of a class when the program is executed. This type of initialization is called the automatic initialization.

 

Constructor Overloading:

            More than one constructor functions can he defined in one class. When more than one constructor functions are defined, each constructor is defined with a different set of parameters. Defining more than one constructor with different set of parameters is called constructor overloading. Constructor overloading is used to initialize different values to class objects.

            When a program that uses the constructor overloading is compiled, C++ compiler checks the number of parameters, their order and data types and marks them differently. When an object of the class is created, the corresponding constructor that matches the number of parameters of the object function is executed. 

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.