Constructor

Constructors

Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object.
class A
{
int x;
public:
A(); //Constructor
};
While defining a constructor you must remember that the name of constructor will be same as the name of the class, and constructors never have return type.
Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.
class A
{
int i;
public:
A(); //Constructor declared
};


A::A() // Constructor definition
{
i=1;
}

Types of Constructors
Constructors are of three types :
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax :
class_name ()
{ Constructor Definition }
Example :
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};


int main()
{
Cube c;
cout << c.side;
}
Output : 10
In this case, as soon as the object is created the constructor is called which initializes its data members.
A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
int side;
};


int main()
{
Cube c;
cout << c.side;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will initialize the object data members to default value, that will be 0 in this case.
Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.
Example :
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};


int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30
By using parameterized construcor in above case, we have initialized 3 objects with user defined values. We can have any number of parameters in a constructor.
Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object. We will study copy constructors in detail later.
Constructor Overloading
Just like other member functions, constructors can also be overloaded. Infact when you have both default and parameterized constructors defined in your class you are having Overloaded Constructors, one with no parameter and other with parameter.
You can have any number of Constructors in a class that differ in parameter list.
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};


int main()
{
Student A(10);
Student B(11,"Ram");
}
In above case we have defined two constructors with different parameters, hence overloading the constructors.
One more important thing, if you define any constructor explicitly, then the compiler will not provide default constructor and you will have to define it yourself.
In the above case if we write Student S; in main(), it will lead to a compile time error, because we haven't defined default constructor, and compiler will not provide its default constructor because we have defined other parameterized constructors.
Destructors
Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it.
class A
{
public:
~A();
};
Destructors will never have any arguments.

Example to see how Constructor and Destructor is called
class A
{
A()
{
cout << "Constructor called";
}


~A()
{
cout << "Destructor called";
}
};


int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1

Single Definition for both Default and Parameterized Constructor
In this example we will use default argument to have a single definition for both defualt and parameterized constructor.
class Dual
{
int a;
public:
Dual(int x=0)
{
a=x;
}
};


int main()
{
Dual obj1;
Dual obj2(10);
}
Here, in this program, a single Constructor definition will take care for both these object initializations. We don't need separate default and parameterized constructors.
-------------------------
Constructor Overloading
Definition
In C++,Constructor is automatically called when object(instance of class) create.It is special member function of the class.Which constructor has arguments thats called Parameterized Constructor.
  • One Constructor overload another constructor is called Constructer Overloading 
  • It has same name of class.
  • It must be a public member.
  • No Return Values.
  • Default constructors are called when constructors are not defined for the classes.
Syntax
class class-name
{
    Access Specifier:
        Member-Variables
        Member-Functions
    public:
        class-name()
        {
            // Constructor code 
        }
         class-name(variables)
        {
            // Constructor code 
        }
        ... other Variables & Functions
}
Example Program
/*  Example Program For Simple Example Program Of Constructor Overloading In C++
    little drops

                 */

#include<iostream>
#include<conio.h>

using namespace std;

class Example        {
    // Variable Declaration
    int a,b;
    public:

    //Constructor wuithout Argument
    Example()            {
    // Assign Values In Constructor
    a=50;
    b=100;
    cout<<"\nIm Constructor";
    }

    //Constructor with Argument
    Example(int x,int y)            {
    // Assign Values In Constructor
    a=x;
    b=y;
    cout<<"\nIm Constructor";
    }

    void Display()    {
    cout<<"\nValues :"<<a<<"\t"<<b;
    }
};

int main()                {
        Example Object(10,20);
        Example Object2;
        // Constructor invoked.
        Object.Display();
        Object2.Display();
        // Wait For Output Screen
        getch();
        return 0;
}

Sample Output
Im Constructor
Im Constructor
Values :10      20
Values :50      100
Constructor Overloading
Constructor can be overloaded in similar way as function overloading. Overloaded constructors have same name(name of the class) but different number of argument passed. Depending upon the number and type of argument passed, specific constructor is called. Since, constructor are called when object is created. Argument to the constructor also should be passed while creating object. Here is the modification of above program to demonstrate the working of overloaded constructors.
/* Source Code to demonstrate the working of overloaded constructors */
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;

public:
Area(): length(5), breadth(2){ } // Constructor without no argument
Area(int l, int b): length(l), breadth(b){ } // Constructor with two argument
void GetLength()
{
cout<<"Enter length and breadth respectively: ";
cin>>length>>breadth;
}
int AreaCalculation() { return (length*breadth); }
void DisplayArea(int temp)
{
cout<<"Area: "<<temp<<endl;
}
};
int main()
{
Area A1,A2(2,1);
int temp;
cout<<"Default Area when no argument is passed."<<endl;
temp=A1.AreaCalculation();
A1.DisplayArea(temp);
cout<<"Area when (2,1) is passed as argument."<<endl;
temp=A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
Explanation of Overloaded Constructors
For object A1, no argument is passed. Thus, the constructor with no argument is invoked which initialises length to 5 and breadth to 2. Hence, the area of object A1 will be 10. For object A2, 2 and 1 is passed as argument. Thus, the constructor with two argument is called which initialiseslength to l(2 in this case) and breadth to b(1 in this case.). Hence the area of object A2 will be 2.
Output
Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as argument.
Area: 2
Constructor Overloading
Just like other member functions, constructors can also be overloaded. Infact when you have both default and parameterized constructors defined in your class you are having Overloaded Constructors, one with no parameter and other with parameter.
You can have any number of Constructors in a class that differ in parameter list.
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};


int main()
{
Student A(10);
Student B(11,"Ram");
}
In above case we have defined two constructors with different parameters, hence overloading the constructors.
One more important thing, if you define any constructor explicitly, then the compiler will not provide default constructor and you will have to define it yourself.
In the above case if we write Student S; in main(), it will lead to a compile time error, because we haven't defined default constructor, and compiler will not provide its default constructor because we have defined other parameterized constructors.
Copy Constructor

A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object.
A copy constructor is a constructor of the form
classname(classname &).
The compiler will use the copy constructors whenever you initialize an instance using values of another instance of the same type.
Copying of objects is achieved by the use of a copy constructor and a assignment operator.

Example :
class Sample
{
int i, j;
}
public:
Sample(int a, int b) // constructor
{
i=a; j=b;
}
Sample (Sample & s) //copy constructor
{
j=s.j ; i=s.j;
cout <<”\n Copy constructor working \n”;
}
void print (void)
{
cout <<i<< j<< ”\n”;

}
:
};

Note : The argument to a copy constructor is passed by reference, the reason being that when an argument is passed by value, a copy of it is constructed. But the copy constructor is creating a copy of the object for itself, thus, it calls itself. Again the called copy constructor requires another copy so again it is called. In fact it calls itself again and again until the compiler runs out of the memory .so, in the copy constructor, the argument must be passed by reference.


The following cases may result in a call to a copy constructor:
When an object is passed by value to a function:
The pass by value method requires a copy of the passed argument to be created for the function to operate upon .Thus to create the copy of the passed object, copy constructor is invoked
If a function with the following prototype :
void cpyfunc(Sample );
// Sample is a class then for the following function call
cpyfunc(obj1); // obj1 is an object of Sample type
the copy constructor would be invoked to create a copy of the obj1 object for use by cpyfunc().


  • When a function returns an object :
When an object is returned by a function the copy constructor is invoked

Sample cpyfunc(); // Sample is a class and it is return type of cpyfunc()

If func cpyfunc() is called by the following statement

obj2 = cpyfunc();

Then the copy constructor would be invoked to create a copy of the value returned by cpyfunc() and its value would be assigned to obj2. The copy constructor creates a temporary object to hold the return value of a function returning an object.

1 & 2 Marks Solved Problems :

Q1 :- Answer the questions after going through the following class. class Exam
{char Subject[20] ;
int Marks ;
public :
Exam() // Function 1
{strcpy(Subject, “Computer” ) ; Marks = 0 ;}
Exam(char P[ ]) // Function 2
{strcpy(Subject, P) ; Marks=0 ;
}
Exam(int M) // Function 3
{strcpy(Subject, “Computer”) ; Marks = M ;}
Exam(char P[ ], int M) // Function 4
{strcpy(Subject, P) ; Marks = M ;}
};
a) Which feature of the Object Oriented Programming is demonstrated using Function 1, Function2, Function 3 and Function 4 in the above class Exam?
Ans:- Function Overloading (Constructor overloading)
b) Write statements in C++ that would execute Function 3 and Function 4 of class Exam.
Ans:- Exam a(10); and Exam b(“Comp”, 10);


Q2 Consider the following declaration :
class welcome
{public:
welcome (int x, char ch); // constructor with parameter
welcome(); // constructor without parameter void compute();
private:
int x; char ch;
};
which of the following are valid statements
welcome obj (33, ‘a9’);
welcome obj1(50, ‘9’);
welcome obj3();
obj1= welcome (45, ‘T’);
obj3= welcome;




Ans.
Valid and invalid statements are




welcome obj (33, ‘a9’);
valid


welcome obj1(50, ‘9’);
valid


welcome obj3();
invalid


obj1= welcome (45, ‘T’);
valid


obj3= welcome;
invalid
2 Marks Practice Problems

Q1 What do you understand by constructor and destructor functions used in classes ? How are these functions different from other member functions ?

Q2 What do you understand by default constructor and copy constructor functions used in classes? How are these functions different from normal constructors ?
Q3 Given the following C++ code, answer the questions (i) & (ii). class TestMeOut
{
public :
~TestMeOut() // Function 1
{ cout << "Leaving the examination hall " << endl; }
TestMeOut() // Function 2
{ cout << "Appearing for examination " << endl; }
void MyWork() // Function 3
{ cout << "Attempting Questions " << endl; }
};
(i) In Object Oriented Programming, what is Function 1 referred as and when does it get invoked/ called ?
(ii) In Object Oriented Programming, what is Function 2 referred as and when does it get invoked/ called ?






















Q.  Answer the following questions (i) and (ii) after going through the following class.
class Interview
{ int Month;
public:
interview(int y)
{Month=y;}
//constructor 1
interview(Interview&t); //constructor 2
};

(i) create an object, such that it invokes Constructor 1

Ans: Interview A(10); //invoking constructor 1 by passing a number.

(ii) write complete definition for Constructer .2

Ans: Interview(Interview &t) //This is a copy constructor.
{
Month=t.Month;
}


Q. Answer the questions (i) and (ii) after going through the following program:

#include <iostream.h>
#include<string.h>
class bazaar
{ char Type[20] ;
char product [20];
int qty ;
float price ;
bazaar() //function 1
{ strcpy (type , “Electronic”) ;
strcpy (product , “calculator”);
qty=10;
price=225;
}
public :
void Disp() //function 2
{ cout<< type <<”-”<<product<<”:” <<qty<< “@” << price << endl ;
}
};
void main ()
{ Bazaar B ; //statement 1
B. disp() ; //statement 2
}
(i) Will statement 1 initialize all the data members for object B with the values given in the function 1 ? (YES OR NO). Justify your answer suggesting thecorrection(s) to be made in the above code.
Ans: No. The reason is the constructor should be defined under the public visibility label.
(ii) What shall be the possible output when the program gets executed ? (Assuming, if required _ the suggested correction(s) are made in the program).
Ans: Possible Output:
Electronic–Calculator:10@225







Q.  Define a class Garments in c++ with following descriptions.
private members :
GCode    of type string
GType     of type string
Gsize      of type intiger
Gfabric   of type istring
Gprice    of type float
A function Assign() which calculate and the value of GPrice as follows.For the value of GFabric “COTTON” ,
GType           GPrice(RS)
TROUSER   1300
SHIRT           1100
For GFabric other than “COTTON”, the above mentioned GPrice gets reduced by 10%
public members:
A constructor to assign initial values of GCode,GType and GFabric with the a word “NOT ALLOTED”and Gsize and Gprice with 0.
A function Input () to the values of the data membersGCode, GType,Gsize and GFabric and invoke the Assign() function.A function Display () which displays the content of all the data members for a garment.



#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<stdio.h>
class Garments
{ char GCode[21],GType[21];
int Gsize;
char Gfabric[21];
float Gprice;
void Assign( )
{
if(strcmp(strupr(Gfabric),"COTTON")==0)
{ if(strcmp(strupr(GType),"TROUSER")==0)
Gprice=1300;
if(strcmp(strupr(GType),"SHIRT")==0)
Gprice=1100;
}
else
{if(strcmp(strupr(GType),"TROUSER")==0)
Gprice=1300*0.90;
if(strcmp(strupr(GType),"SHIRT")==0)
Gprice=1100*0.90;
}
}
public:
Garments( )
{
strcpy(GCode,"NOT ALLOTED");
strcpy(GType,"NOT ALLOTED");
Gsize=0;
strcpy(Gfabric,"NOT ALLOTED");
Gprice=0;
}
void Input( )
{ cout<<"\nEnter the Grament Code: ";
gets(GCode);
cout<<"\nEnter the Garment Type: ";
gets(GType);
cout<<"\nEnter the Garment Size: ";
cin>>Gsize;
cout<<"\nEnter the Garment Fabric: ";
gets(Gfabric);
Assign( );
} void display( )
{ cout<<"\nThe Garment Code: "<<GCode;cout<<"\nThe Garment Type: "<<GType;
cout<<"\nThe Garment Size: "<<Gsize;
cout<<"\nThe Garment Fabric: "<<Gfabric;
cout<<"\nThe Garment Price: "<<Gprice;
}
};
void main( )
{ Garments G;
G.Input( );
G.display( ); }

Definition
In C++,Constructor is automatically called when object(instance of class) create.It is special member function of the class.
  • It has same name of class.
  • It must be a public member.
  • No Return Values.
  • Default constructors are called when constructors are not defined for the classes.
Copy Constructor:
One Object Member Variable Values assigned to Another Object Member Variables  is called copy constructor. 
Syntax
class class-name
{
    Access Specifier:
        Member-Variables
        Member-Functions
    public:
        class-name(variable)
        {
            // Constructor code 
        }
        
        ... other Variables & Functions
}

yntax : Argument In Main Function

ClassName Object1(value);
ClassName Object2=Object1;

Example Program

/*  Example Program For Simple Example Program Of Copy Constructor Overloading In C++
    little drops @ thiyagaraaj.com

    Coded By:THIYAGARAAJ MP             */

#include<iostream>
#include<conio.h>

using namespace std;

class Example        {
    // Variable Declaration
    int a,b;
    public:

    //Constructor with Argument
    Example(int x,int y)            {
    // Assign Values In Constructor
    a=x;
    b=y;
    cout<<"\nIm Constructor";
    }

    void Display()    {
    cout<<"\nValues :"<<a<<"\t"<<b;
    }
};

int main()                {
        Example Object(10,20);

        //Copy Constructor
        Example Object2=Object;

        // Constructor invoked.

        Object.Display();
        Object2.Display();

        // Wait For Output Screen
        getch();
        return 0;
}
Sample Output
Im Constructor
Values :10      20
Values :10      20




Comments

Popular posts from this blog

WAP to get roll numbers and marks of the student of a class (get from the user) and store these details into a file called Marks.dat

WAP that obtains the rotation factor and rotates the array as per it.

WAP to illustrate working of call-by-reference method of a function invoking.