C++ Constructors

C++ Constructors

A constructor is used to initialize the objects of its class.

Constructor have the same name as that of its class name. The constructor is invoked whenever object of its associated class is created. It is called constructor because it construct the values of data members of the class.

A C++ Constructors is declared and defined as follow:

class  test

{     Int a , b;

public:

test (void);                        //constructor declared

……….

………..

};

test : : test (void)         //constructor defined

{

a = 0, b=0;

}

A C++ Constructors  that accept no parameters is called the default constructor. The  default constructor for class test  is test :: test(). If no  such constructor is not defined, then compiler supplies a  default constructor. Therefore , a statement such as:

test a ;

invokes the default constructor of  the compiler to create the object a.

Parameterized C++ Constructors

The constructor test(), defined above , initializes the data members of the objects to zero .However, in practice it may be necessary to initialize the various data elements of  different objects with different values when they are created. C++ permits us to achieve this objective by passing arguments to the constructor function when the objects are created. The constructor s that can take arguments are called parameterized constructor.




Follow Us

Contact Us

tutorialworldin@yahoo.com

Back to Top