CrackAlgo infosys interview experience

What is Constructor

What is Constructor

A constructor is a member function with a name same as that of the class name used to initialize the instant variable of objects.

Need of using a Constructor

When you create various object of class, the data members are automatically allocated under each object. If you are allowed to initialize the data members at the time of creating a class then the data member corresponding to all the objects will poses the same initial values. But in practice you would like to have separate initial values for different objects. In case you use member method to initialize the data members then you may need to call it every time separately after creating an object.

Syntax to create a constructor

class  <class name>

{

     <data member 1>

     <data member 2>
     .......
     ......

     <data member n>

    <class name> ()

   {

        <data member 1 = value>

        <data member 2 = value>
        .......
        .......

        <data member n = value>

    }

}

 

example:-

class item

{

     int a;

     float b;

     char c;

     String s;

     item()

     { 

         a=9;

         b=9.0;

         c='A';

         s= "Hello";

     }

}

 

Invoking a constructor

A constructor can be invoked when we create an object of a constructor.

Syntax:-

<class name> <object name> = new <constructor>

Example:-

What is Constructor
What is Constructor

 

Recommended Post:-

codechef problems:-

Wipro :-

Infytq :-

Key Points;-

Hackerrank:-

C-tutorial:-

See more:-

 

Leave a Reply

Your email address will not be published.