Search This Blog

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>
usingnamespacestd;
classArea
{
private:
intlength;
intbreadth;

public:
Area(): length(5), breadth(2){ } // Constructor without no argument
Area(intl, intb): length(l), breadth(b){ } // Constructor with two argument
voidGetLength()
{
cout<<"Enter length and breadth respectively: ";
cin>>length>>breadth;
}
intAreaCalculation() { return(length*breadth); }
voidDisplayArea(inttemp)
{
cout<<"Area: "<<temp<<endl;
}
};
intmain()
{
AreaA1,A2(2,1);
inttemp;
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);
return0;
}
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.
CopyConstructor

AcopyconstructorisaspecialconstructorintheC++programminglanguageused to createa newobjectas a copyofanexisting object.
A copyconstructoris aconstructoroftheform
classname(classname&).
Thecompiler will usethecopyconstructors wheneveryou initializean instanceusingvalues ofanother instanceofthesametype.
Copyingofobjects is achieved bytheuseofacopyconstructorandaassignment operator.

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

}
:
};

Note:Theargumenttoacopyconstructorispassedbyreference,thereasonbeingthatwhen anargumentispassedbyvalue,acopyofitisconstructed.Butthecopyconstructoriscreating acopyoftheobjectforitself,thus, it calls itself.Againthecalledcopyconstructorrequires anothercopysoagainitiscalled. Infactitcalls itselfagainandagainuntilthecompilerruns out ofthememory.so, inthecopyconstructor, theargumentmust bepassed byreference.


Thefollowing cases may resultina call to a copy constructor:
Whenanobjectis passed by valueto a function:
Thepassby valuemethodrequiresacopy ofthepassedargumenttobecreatedforthe functiontooperateupon.Thustocreatethecopy of thepassedobject,copy constructoris invoked
Ifafunction with thefollowingprototype:
void cpyfunc(Sample);
// Sampleis aclass then forthefollowingfunction call
cpyfunc(obj1); // obj1 is an object ofSampletype
thecopyconstructorwould beinvoked to createacopyoftheobj1 object foruse bycpyfunc().


  • When a function returns an object :
When an object is returned byafunction thecopyconstructoris invoked

Samplecpyfunc(); // Sampleis a class anditis returntypeofcpyfunc()

Iffunccpyfunc() is called bythefollowingstatement

obj2 = cpyfunc();

Thenthecopy constructorwouldbeinvokedtocreateacopy of thevaluereturnedby cpyfunc()anditsvaluewouldbeassignedtoobj2.Thecopy constructorcreatesa temporaryobject to hold thereturn valueofafunction returning an object.

1&2Marks SolvedProblems :

Q1 :-Answerthequestions aftergoingthrough thefollowing class. class Exam
{charSubject[20];
int Marks ;
public:
Exam() // Function 1
{strcpy(Subject, Computer) ; Marks = 0 ;}
Exam(charP[]) // Function 2
{strcpy(Subject, P) ; Marks=0 ;
}
Exam(int M) // Function 3
{strcpy(Subject, Computer”) ; Marks = M ;}
Exam(charP[], int M) // Function 4
{strcpy(Subject, P) ; Marks = M ;}
};
a) Which featureoftheObject Oriented Programmingis demonstrated using Function 1, Function2, Function 3 and Function 4 in theaboveclass Exam?
Ans:- Function Overloading (Constructoroverloading)
b) Writestatements in C++that would executeFunction 3 and Function 4 ofclass Exam.
Ans:-Exam a(10); and Exam b(Comp, 10);


Q2 Considerthefollowingdeclaration :
class welcome
{public:
welcome(int x, charch); // constructorwith parameter
welcome(); // constructorwithout parameter void compute();
private:
int x; charch;
};
which ofthefollowingarevalid statements
welcomeobj (33, a9);
welcomeobj1(50, 9);
welcomeobj3();
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
2MarksPractice Problems

Q1What do you understand byconstructorand destructorfunctions used in classes ? How are these functions differentfrom othermemberfunctions?

Q2What do you understand bydefault constructorand copyconstructorfunctions used in classes?How arethesefunctions different from normal constructors ?
Q3Given thefollowing C++code,answerthequestions (i) &(ii). class TestMeOut
{
public:
~TestMeOut() // Function 1
{ cout <<"Leavingtheexamination hall "<<endl; }
TestMeOut() // Function 2
{ cout <<"Appearingforexamination "<<endl; }
void MyWork() // Function 3
{ cout <<"Attempting Questions "<<endl; }
};
(i)In ObjectOriented Programming, what is Function 1 referred asand when does it get invoked/ called ?
(ii)InObject Oriented Programming, what is Function 2 referred asand 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




No comments:

Post a Comment

How do I crack the GSOC in the field of machine learning?

How do I crack the GSOC in the field of machine learning? Working as a student at Google Summer of Code demands for your dedication an...