Module 3 CPP New

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

1|Page

Module III-Constructors and Destructors

MODULE 3 SYLLABUS: Constructers and Destructors, Overloading Constructors- Default


constructor-Parameterized constructor-Copy constructor- Multiple constructors ,Constructors
with default arguments- Dynamic constructor-Destructors- Operator overloading- Unary and
Binary operator overloading- Overloading using friends- Rules for overloading- Type
conversion.

Constructors

A constructor is a special member function whose task is to initialize the objects of its class
When a constructor is declared for a class, initialization of the class objects becomes
mandatory.It is special because its name is same as the class name.The constructor is invoked
whenever an object of its associated class is created.It is called constructor because it constructs
the values of data members of the class.It is defined like other member functions of the class,
i.e., either inside the class definition or outside the class definition.

There is no need to write any statement to invoke the constructor function.If a ‘normal’ member
function is defined for zero initialization, we would need to invoke this function for each of the
objects separately.A constructor that accepts no parameters is called the default
constructor.The default constructor for class A is A : : A ( )

Characteristics of Constructors
1. They should be declared in the public section.
2. They are invoked automatically when the objects are created.
3. They do not have return types, not even void and they cannot return values.
4. They cannot be inherited, though a derived class can call the base class constructor.
5. Like other C++ functions, Constructors can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to their addresses.
8. An object with a constructor (or destructor) cannot be used as a member of a union.
9. They make ‘implicit calls’ to the operators new and delete when memory allocation is
required.
10. When a constructor is declared for a class initialization of the class objects becomes
mandatory.

Types of constructors
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Dynamic Constructor

Default Constructor

1
2|Page

A constructor without any parameters is called as default constructor.If no constructors are


available for a class, the compiler implicitly creates a default parameterless constructor and a
null body.
Drawback of default constructor is every instance of the class will be initialized to same
values and it is not possible to initialize each instance of the class to different values.
Default Constructor-example
#include <iostream.h>
class Defal
{
public:
int x;
int y;
Defal(){x=y=0;}
};
void main()
{
Defal A;
cout << "Default constructs x,y value::"<< A.x <<" , "<< A.y << "\n";
return 0;
}
Result:
Default constructs x,y value:: 0,0
In the above example a default constructor has the default value of "0" for both the parameters

//To demonstrate a constructor


#include <iostream.h>
#include <conio.h>
class rectangle
{
private :
float length, breadth;
public:
rectangle ()//constructor definition
{
//displayed whenever an object is created
cout<<”I am in the constructor”;
length=10.0;
breadth=20.5;
}
float area()
{
return (length*breadth);
}
};
void main()

2
3|Page

{
clrscr();
rectangle rect; //object declared
cout<<”\nThe area of the rectangle with default parameters is:”<<rect.area()<<”sq.units\n”;
getch();
}

Parameterized Constructors
It may be necessary to initialize the various data elements of different objects with different
values when they are created.This is achieved by passing arguments to the constructor function
when the objects are created.The constructors that can take arguments are called
parameterized constructors.
Note:-The parameters can be of any type except that of the class to which it belongs
class add
{
int m, n ;
public :
add (int, int) ;
------
};
add : : add (int x, int y)
{
m = x; n = y;
}
When a constructor is parameterized, we must pass the initial values as arguments to the
constructor function when an object is declared. This can be done in two ways
1. By calling constructor explicitly
 add sum = add(2,3); //explicit call
This statement creates an add object sum and passes the values 2 and 3 to it
2. By calling constructor implicitly
 add sum(2,3)
This shorthand method is used often as it is easy to implement
Parameterized Constructor-example
#include <iostream.h>
class Crectangle
{
int width, height;
public:
CRectangle (int,int);
int area ()
{
return (width*height);

3
4|Page

}
};
CRectangle::CRectangle (int a, int b)
{
width = a;
height = b;
}
int main ()
{
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

Multiple Constructors in a Class


C++ permits to use more than one constructors in a single class.
Add( ) ; // No arguments
Add (int, int) ; // Two arguments

class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}
add (int a, int b)
{m = a ; n = b ;}
};
The first constructor receives no arguments.
The second constructor receives two integer arguments.
Add a1;
 Would automatically invoke the first constructor and set both m and n of a1 to zero.
Add a2(10,20);
 Would call the second constructor which will initialize the data members m and n of a2
to 10 and 20 respectively.

Constructor Overloading
More than one constructor functions can be defined in a class. This is called Constructor
Overloading
Multiple Constructors in a Class
class complex
{
float x, y ;
public :

4
5|Page

complex ( ) { }
complex (float a)
{x=y=a;}
complex (float r, float i)
{x=r;y=i}
------
};
complex ( ) { }
This contains the empty body and does not do anything.This is used to create objects without
any initial values.
C + + compiler has an implicit constructor which creates objects, even though it was not
defined in the class.This works well as long as we do not use any other constructor in the class.
However, once we define a constructor, we must also define the “do-nothing” implicit
constructor.

Constructor Overloading
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<string.h> //for strcpy()
class figure
{
private:
float radius, side1,side2,side3; //data members
char shape[10];
public:
figure(float r) //constructor for circle
{
radius=r;
strcpy (shape, “circle”);
}
figure (float s1,float s2) //constructor for rectangle
{
side1=s1;
side2=s2;
side3=radius=0.0; //has no significance in rectangle strcpy(shape,”rectangle”);
}
figure (float s1, floats2, float s3) //constructor for triangle
{
side1=s1;
side2=s2;
side3=s3;
radius=0.0;
strcpy(shape,”triangle”);
}

5
6|Page

void area() //calculate area


{
float ar,s;
if(radius==0.0)
{
if (side3==0.0)
ar=side1*side2;
else
ar=3.14*radius*radius;
cout<<”\n\nArea of the “<<shape<<”is :”<<ar<<”sq.units\n”;
}
}
};
void main()
{
clrscr();
figure circle(10.0); //object initialized using constructor
figure rectangle(15.0,20.6);//object initialized using constructor
figure triangle(3.0, 4.0, 5.0); //object initialized using constructor
rectangle.area();
triangle.area();
getch();
}

Constructors with Default Arguments


It is possible to define constructors with default arguments.
Consider complex (float real, float imag = 0);
 The default value of the argument imag is zero.
 complex C1 (5.0) assigns the value 5.0 to the real variable and 0.0 to imag.
 complex C2(2.0,3.0) assigns the value 2.0 to real and 3.0 to imag.
A : : A ( ) à Default constructor
A : : A (int = 0) à Default argument constructor
The default argument constructor can be called with either one argument or no arguments.
When called with no arguments, it becomes a default constructor.

Copy Constructor
A copy constructor is used to declare and initialize an object from another object.
integer (integer & i) ;
integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
The process of initializing through a copy constructor is known as copy initialization.
The statement
I 2 = I 1;
will not invoke the copy constructor.
If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2, member-by-
member.

6
7|Page

A reference variable has been used as an argument to the copy constructor.We cannot pass
the argument by value to a copy constructor.
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}
add (int a, int b)
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n ;}
};
Add a3(a2);
Would invoke the third constructor which copies the values of a2 into a3.
This type of constructor is called the “copy constructor”.

Dynamic Initialization of Objects


Providing initial value to objects at run time.This provides the flexibility of using different format
of data at run time depending upon the situation.
Advantage –We can provide various initialization formats, using overloaded constructors.

//Illustration of dynamic initialization of objects


#include <iostream.h>
#include <conio.h>
class employee
{
int empl_no;
float salary;
public:
employee() //default constructor
{}
employee(int empno,float s)//constructor with arguments
{
empl_no=empno;
salary=s;
}
employee (employee &emp)//copy constructor
{
cout<<”\ncopy constructor working\n”;
empl_no=emp.empl_no;
salary=emp.salary;
}
void display (void)
{
cout<<”\nEmp.No:”<<empl_no<<”salary:”<<salary<<end1;

7
8|Page

}
};
void main()
{
int eno;
float sal;
clrscr();
cout<<”Enter the employee number and salary\n”;
cin>>eno>>sal;
employee obj1(eno,sal);//dynamic initialization of object
cout<<”\nEnter the employee number and salary\n”;
cin>eno>>sal;
employee obj2(eno,sal); //dynamic initialization of object
obj1.display(); //function called
employee obj3=obj2; //copy constructor called
obj3.display();
getch();
}

Dynamic Constructors
The constructors can also be used to allocate memory while creating objects.This will enable the
system to allocate the right amount of memory for each object when the objects are not of the
same size. Allocation of memory to objects at the time of their construction is known as dynamic
construction of objects. The memory is created with the help of the new operator.

Destructors
A destructor is used to destroy the objects that have been created by a constructor.
Like constructor, the destructor is a special member function whose name is the same as the
class name but is preceded by a tilde.
eg: ~ integer ( ) { }
 A destructor never takes any argument nor does it return any value.
 It will be invoked implicitly by the compiler upon exit from the program – or block or
function as the case may be – to clean up storage that is no longer accessible.
 It is a good practice to declare destructors in a program since it releases memory space
for further use.
 Whenever new is used to allocate memory in the constructor, we should use delete to
free that memory.
 It is mainly used to de-allocate dynamic memory locations
 Destructors cannot be overloaded

example on constructors and destructors

#include <iostream.h>
class CRectangle {
int *width, *height;

8
9|Page

public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};
CRectangle::CRectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}
CRectangle::~CRectangle ()
{
delete width;
delete height;
}
int main ()
{
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

9
10 | P a g e

Overloading in C++
It is one of the many exciting features of C++.C++ has ability to provide the operators with a
special meaning for a data type.The mechanism of giving such special meanings to an operator is
called operator overloading.We can overload (give additional meaning to) all the C++ operators
except:
 Class member access operators ( . & .*)
 Scope resolution operators ( : : )
 Size operator (sizeof)
 Conditional operators (? : )
When an operator is overloaded, its original meaning is not lost.

Defining Operator Overloading


To define an additional task to an operator, we must specify what it means in relation to the
class to which the operator is applied.This is done with the help of a special function called
operator function.
return type class-name : :operator op (arg-list)
{
Function body // task defined
}
return type is the type of value returned by the specified operation.
op is the operator being overloaded.
op is preceded by the keyword operator.
operator op is the function name.
Operator Function must be either member function (non-static) or friend function.
The basic difference :
A friend function will have only one argument for unary operators and two for binary operators.
A member function has no arguments for unary operators and one argument for binary
operators.
This is because the object used to invoke the member function is passed implicitly and therefore
is available for the member function.
Arguments may be passed either by value or by reference.

Process of Operator Overloading


The process of overloading involves the following steps:
 Create a class that defines the data type that is to be used in the overloading operation.
 Declare the operator function operator op( ) in the public part of the class. It may be
either a member function or a friend function.
 Define the operator function to implement the required operations.

Overloaded operator functions can be invoked by expressions such as:

For unary operators: op x or x op

10
11 | P a g e

For binary operators: x op y


op x or x op would be interpreted as

for a friend function: operator op (x)


for a member function: x.operator op ( )

x op y would be interpreted as

for a friend function: operator op (x,y)


for a member function: x.operator op (y)

Overloading Unary Operators


Consider a unary minus operator:
It takes just one operand.
It changes the sign of an operand when applied to a basic data item.
The unary minus when applied to an object should change the sign of each of its data items.
Overloading Binary Operators
As a rule, in overloading binary operators,
the left-hand operand is used to invoke the operator function and
the right-hand operand is passed as an argument.
return complex((x+c.x), (y+c.y));
The compiler invokes an appropriate constructor, initializes an object with no name and
returns the contents for copying into an object.Such an object is called a temporary object and
goes out of space as soon as the contents are assigned to another object.

Overloading Binary Operators Using Friends


Friend function requires two arguments to be explicitly passes to it.Member function requires
only one.
friend complex operator+(complex, complex);
complex operator+(complex a, complex b)
{
return complex((a.x + b.x),(a.y + b.y));
}
We can use a friend function with built-in type data as the left-hand operand and an object as
the right-hand operand.

Rules For Overloading Operators


 Only existing operators can be overloaded. New operators cannot be created.
 The overloaded operator must have at least one operand that is of user-defined type.
 We cannot change the basic meaning of an operator.
 Overloaded operators follow the syntax rules of the original operators.
 The following operators that cannot be overloaded:
o Size of Size of operator
o . Membership operator
o .* Pointer-to-member operator

11
12 | P a g e

o :: Scope resolution operator


o ?; Conditional operator
 The following operators can be over loaded with the use of member functions and not
by the use of friend functions:
o Assignment operator =
o Function call operator( )
o Subscripting operator [ ]
o Class member access operator ->
 Unary operators, overloaded by means of a member function, take no explicit
arguments and return no explicit values, but, those overloaded by means of a friend
function, take one reference argument.
 Binary operators overloaded through a member function take one explicit argument and
those which are overloaded through a friend function take two explicit arguments.
 When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.
 Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must
not attempt to change their own arguments.

Type Conversions
 In C programming language, when different types of constants and variables are used in expression,
C automatically perform type conversion based on some fixed rules. In assignment operation,
variable at the right hand side is automatically converted to the type of the variable on the left. The
Same can also be possible in C++ programming language.

int a ;

float b = 3.14654;

a = b;

 Here ‘b’ is float variable but it is at the right side in the assignment statement so converted into the
integer format.

 But this automated type promotion will work well if both data types are of primary data type or both
are of same user-defined data type. But it will create problem when one data type is user-defined
data type and another is primary data type. So for that we have to use some special function for type
conversion as in such cases automatic type conversion can not be performed by the language itself.

 There are three types of type conversion are possible:

1. Conversion from basic type to the class type.

12
13 | P a g e

2. Conversion from class type to basic type.


3. Conversion from one class to another class type.

Conversion from Basic type to the Class type

 In this type of conversion the source type is basic type and the destination type is class type. Means
basic data type is converted into the class type.

 For example we have class employee and one object of employee ‘emp’ and suppose we want to


assign the employee code of employee ‘emp’ by any integer variable say ‘Ecode’ then the statement
below is the example of the conversion from basic to class type.

emp = Ecode ;

 Here the assignment will be done by converting “Ecode” which is of basic or primary data type into
the class type.

Conversion from Class type to Basic type

 In this type of conversion the source type is class type and the destination type is basic type. Means  
class data type is converted into the basic type.

 For example we have class employee and one object of employee ‘emp’ and suppose we want to


assign the employee code of employee object ‘emp’ to any integer variable say ‘Ecode’ then the
statement below is the example of the conversion from class to basic type.

Ecode = emp ;

 Here the assignment will be done by converting “emp” object which is of class type into the basic or
primary data type.

Conversion from one Class to another Class type

 In this type of conversion both the type that is source type and the destination type are of class type.
Means  the source type is of class type and the destination type is also of the class type. In other
words, one class data type is converted into the another class type.

 For example we have two classes one for “computer” and another for “mobile”. Suppose if we wish
to assign “price” of computer to mobile then it can be achieved by the statement below which is the
example of the conversion from one class to another class type.

mob = comp ; // where mob and comp are the objects of mobile and computer classes respectively.

 Here the assignment will be done by converting “comp” object which is of class type into
the “mob” which is another class data type.

13
14 | P a g e

“Basic type to Class type Conversion”.

As mentioned before, in this type of conversion the source type is basic type and the destination
type is class type. Means basic data type is converted into the class type.

For example we have class employee and one object of employee ‘emp’ and suppose we want to


assign the employee code of employee ‘emp’ by any integer variable say ‘Ecode’ then the
statement below is the example of the conversion from basic to class type.

emp = Ecode ;

Here the assignment will be done by converting “Ecode” which is of basic or primary data type
into the class type.

The conversion from basic type to the class type can be performed by two ways:

Using constructor
Using Operator Overloading

Using Constructor

We can use constructor to perform type conversion during the object creation.


Consider the following example with class ‘Time’ in which we want to assign total time in
minutes by integer variable ‘duration’.

To achieve that we have implemented one constructor function which accepts one argument of
type integer as follow:

/* Program to convert basic type to class type using constructor */

#include <iostream.h>
#include <conio.h>
class Time
{
int hrs,min;
public:
Time(int);
void display();
};

Time :: Time(int t)
{
cout<<"Basic Type to ==> Class Type Conversion..."<<endl;
hrs=t/60;
min=t%60;
}

void Time::display()
{

14
15 | P a g e

cout<<hrs<< ": Hours(s)" <<endl;


cout<<min<< " Minutes" <<endl;
}

void main()
{
clrscr();

int duration;
cout<<"Enter time duration in minutes";
cin>>duration;

Time t1=duration;

t1.display();
getch();
}

Here, we have created an object “t1” of class “Time” and during the creation we have assigned
integer variable “duration”. It will pass time duration to the constructor function and assign to
the “hrs” and “min” members of the class “Time”.

We have to note that during type conversion using the constructor we can pass only one
argument and we can do type conversion at the type of initialization only.

Using Operator Overloading

We can also achieve type conversion by operator overloading.


We can overload assignment operator for this purpose.
Above example of Time class can be rewritten for type conversion using operator overloading
concept to overload the assignment operator (=) as follow:

/* Program to convert from basic type to class type using operator overloading */

#include <iostream.h>
#include <conio.h>
class Time
{
int hrs,min;
public:
void display();
void operator=(int); // overloading function
};
void Time::display()
{
cout<<hrs<< ": Hour(s) "<<endl ;
cout<<min<<": Minutes"<<endl ;
}

void Time::operator=(int t)
{

15
16 | P a g e

cout<<"Basic Type to ==> Class Type Conversion..."<<endl;


hrs=t/60;
min=t%60;
}

void main()
{
clrscr();
Time t1;
int duration;
cout<<"Enter time duration in minutes";
cin>>duration;
cout<<"object t1 overloaded assignment..."<<endl;
t1=duration;
t1.display();
cout<<"object t1 assignment operator 2nd method..."<<endl;
t1=(duration);
t1.display();
getch();
}
By using overloaded assignment operator we can perform the type conversion at any place in
program.

 class type to basic type  conversion

In this type of conversion the source type is class type and the destination type is basic type. Means   class data type
is converted into the basic type.

For example we have class Time and one object of Time class ‘t’ and suppose we want to assign the total time of
object ‘t’ to any integer variable say ‘duration’ then the statement below is the example of the conversion from
class to basic type.

duration= t ; // where, t is object and duration is of basic data type

Here the assignment will be done by converting “t” object which is of class type into the basic or primary data type.
It requires special casting operator function for class type to basic type conversion. This is known as the  conversion
function. The syntax for the conversion function is as under:

operator typename( )

….

….

….

For example suppose we want to assign time in hours and minutes in the form of total time in minutes into one
integer variable “duration” then we can write the type conversion function as under:

16
17 | P a g e

/* Program to demonstrate Class type to Basic type conversion. */

#include "iostream.h"

#include "conio.h"

#include "iomanip.h"

class Time

int hrs,min;

public:

Time(int ,int); // constructor

operator int(); // casting operator function

~Time() // destructor

cout<<"Destructor called..."<<endl;

};

Time::Time(int a,int b)

cout<<"Constructor called with two parameters..."<<endl;

hrs=a;

min=b;

Time :: operator int()

17
18 | P a g e

cout<<"Class Type to Basic Type Conversion..."<<endl;

return(hrs*60+min);

void main()

clrscr();

int h,m,duration;

cout<<"Enter Hours ";

cin>>h;

cout<<"Enter Minutes ";

cin>>m;

Time t(h,m); // construct object

duration = t; // casting conversion OR duration = (int)t

cout<<"Total Minutes are "<<duration;

cout<<"2nd method operator overloading "<<endl;

duration = t.operator int();

cout<<"Total Minutes are "<<duration;

getch();

Notice the statement in above program where conversion took place.

      duration = t;

We can also specify the casting type and write the same statement by the following way to achieve the
same result.

18
19 | P a g e

    duration = (int) t;          // Casting

The conversion function should satisfy the following condition:

It must be a class member.

It must not specify the return value even though it returns the value.

It must not have any argument.

Class to class type conversion

In this type of conversion both the type that is source type and the destination type are of class type.
Means  the source type is of class type and the destination type is also of the class type. In other words,
one class data type is converted into the another class type.

For example we have two classes one for “computer” and another for “mobile”. Suppose if we wish to
assign “price” of computer to mobile then it can be achieved by the statement below which is the example
of the conversion from one class to another class type.

mob = comp ; // where mob and comp are the objects of mobile and computer classes respectively.

Here the assignment will be done by converting “comp” object which is of class type into the “mob” which
is another class data type.

Conversion from one class to another class can be performed either by using the constructor or type
conversion function.

Using Conversion Function-operator overload

The following program demonstrates conversion from one class to another class type with the help of
conversion function where, we have overloaded “=” operator for conversion purpose.

/* Program to convert one class to another class

#include "iostream.h"
#include "conio.h"
#include "iomanip.h"

class inventory1
{
int ino,qty;
float rate;
public:
inventory1(int n,int q,float r)
{
ino=n;
qty=q;
rate=r;
}
inventory1()
{
cout<<"\n Inventory1's Object Created";
}
int getino()

19
20 | P a g e

{
return(ino);
}
float getamt()
{
return(qty*rate);
}
void display()
{
cout<<endl<<"ino = "<<ino<<" qty = "<<qty<<" rate = "<<rate;
}
};
class inventory2
{
int ino;
float amount;
public:

void operator=(inventory1 I)
{
ino=I.getino();
amount=I.getamt();
}
void display()
{
cout<<endl<<"ino = "<<ino<<" amount = "<<amount;
}
};
void main()
{
clrscr();
inventory1 I1(1001,30,75);
inventory2 I2;
I2=I1;
//inventory2 I2=I1;
I1.display();
I2.display();
getch();
}

In the below program we have two classes “Time” and “Minute” respectively in which we have tried to


convert from Time class to Minute class.

/* Program to convert class Time to another class Minute.

#include "iostream.h"
#include "conio.h"
#include "iomanip.h"
class Time
{
int hrs,min;
public:
Time(int h,int m)
{
hrs=h;
min=m;
}

20
21 | P a g e

Time()
{
cout<<"\n Time's Object Created";
}
int getMinutes()
{
int tot_min = ( hrs * 60 ) + min ;
return tot_min;
}
void display()
{
cout<<"Hours: "<<hrs<<endl ;
cout<<" Minutes : "<<min <<endl ;
}
};
class Minute
{
int min;
public:

Minute()
{
min = 0;
}
void operator=(Time T)
{
min=T.getMinutes();
}
void display()
{
cout<<"\n Total Minutes : " <<min<<endl;
}
};
void main()
{
clrscr();
Time t1(2,30);
t1.display();
Minute m1;
m1.display();

m1 = t1; // conversion from Time to Minute

t1.display();
m1.display();
getch();
}

21

You might also like