Академический Документы
Профессиональный Документы
Культура Документы
UNIT-II
Constructors default constructor Parameterized constructors Constructor with dynamic allocation
copy constructor destructors operator overloading overloading through friend functions overloading the
assignment operator type conversion explicit constructor.
Constructors
Definition:
The constructor is a special member function whose task is to initialize the objects of its class. It takes class
name as function name and with no return types. The constructor is invoked whenever an object of its class is
created.
What is the use of Constructor?
The main use of constructors is to initialize objects. The process of initialization is automatically carried
out by the use of a special member function called a constructor.
It is a function used to initialize the data of an object of a class.
1.
Its name same as class name.
2.
It cannot return anything, even void.
3.
A class can have more than one constructor with different parameter list.
4.
Default constructor has no parameters.
Constructors called automatically by new operator when class object is declared.
General Syntax for Constructor
Constructor is a special member function that takes the same name as the class name and it wont have any
return type even void.
Syntax:
classname(argument_list);
The constructor is automatically invoked when an object is created. Constructors used to initialize the
elements of a class at the time of object declaration itself. The various types of constructors are
1. Default constructors
2. Parameterized constructors
3. Copy constructors
Default Constructor: **
This constructor has no arguments in it, called default constructor. Default Constructor is also called as no
argument constructor. The constructor is automatically invoked when an object is created. We cannot invoke
constructors with objects of the class.
Default constructors are used to set initial value for the corresponding class elements.
Syntax:
classname();
Special 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.
4. They cannot be inherited.
5. They can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer their addresses.
8. They make implicit calls to new and delete operators when memory allocation and deallocation is
required.
For example:
#include<iostream.h>
#include<conio.h>
class complex
{
float real,imag;
public:
complex()
//Default Constructor
{
real=10;
imag=0.5;
}
void display()
{
cout<<"Complex number:"<<real<<"+j"<<imag;
}
};
int main()
{
complex c;
}
Output
Complex number:10+j0.5
c.display();
Parameterized Constructor**
The constructors that can take arguments are called parameterized constructors. We must pass the initial
values as arguments to the constructor function when an object is declared. There are two ways to invoke
parameterized constructors.
1. By calling the constructor explicitly.
Eg: Student s=Student(1,xx);
2. By calling the constructor implicitly
Eg: Student s(1,xx);
Syntax:
classname(argument_list);
For example:
#include<iostream.h>
#include<conio.h>
class complex
{
public:
complex(float r,float i)
{
cout<<"Complex number:"<<r<<"+j"<<i;
}
};
int main()
{
complex c(2,4);
}
Output:
Complex number:2+j4
{
real=0;
imag=0;
}
complex(float r,float i)
// constructor 2-parameterized constructor(2 arguments)
{
real=r;
imag=i;
}
void display()
{
cout<<"Complex number:"<<real<<"+j"<<imag<<endl;
}
};
int main()
{
complex c1;
c1.display();
complex c2(3,5);
c2.display();
}
Output:
Complex number:0+j0
Complex number:3+j5
#include<iostream.h>
class complex
{
public:
float real,imag;
complex()
{
real=0;
imag=0;
}
complex(float r,float i)
{
real=r;
imag=i;
}
friend complex add(complex c1,complex
c2);
};
complex add(complex c1,complex c2)
{
complex c3;
c3.real=c1.real+c2.real;
c3.imag=c1.imag+c2.imag;
return c3;
}
int main()
{
complex c1;
complex c2(3,5);
complex c3;
c3=add(c1,c2);
cout<<"Sum="<<c3.real<<"+j"<<c3.imag;
}
Copy constructor:**
A Copy Constructor is used to declare and initialize an object from another object. One of the most
important forms of an overloaded constructor is the copy constructor. The purpose of the copy constructor is
to initialize a new object with data copied from another object of the same class.
Syntax:
class classname
{
public:
classname(classname &object)
{
// constructor body
}
};
Invoking copy constructor:
1. By calling the copy constructor explicitly.
Eg: complex c2=c1;
2. By calling the constructor implicitly
Eg: complex c2(c1);
Example:
#include<iostream.h>
class complex
{
float real,imag;
public:
complex(float r,float i);
complex(complex &c1);
void display();
};
complex::complex(float r,float i)
{
real=r;
imag=i;
}
void complex::display()
{
cout<<real<<"+j"<<imag;
}
complex::complex(complex &c1)
{
real=c1.real;
imag=c1.imag;
}
int main()
{
complex c1(2,4);
c1.display();
complex c2(c1);
//implicit call
c2.display();
complex c3=c1;
//explicit call
}
Definition:
If the memory space for the constructor (memory variable) is allocated during the
constructor calling, then it is called as dynamic constructor.
Dynamic memory allocation for object can be done with the help of operator new.
Depending upon the size of the values in the variable, the memory occupation of the object varies.
Memory de-allocation can be done with the help of delete operator.
Output
The given number is:3
Object memory deallocated
Destructor**
Definition:
A destructor is a special member function to deallocate the memory which are constructed by
constructors.
Destructors used to destroy the object and release the memory.
Like a constructor, destructor is member function whose name is the same as the class name but is
preceded by a tilde(~).
It is invoked automatically to reclaim all the resources allocated to the object when the object goes
out of scope and is no longer needed.
Syntax:
class classname
{
public:
~classname()
{
//destructor body
}
};
A destructor must be declared in the public section of a class so that it is accessible to all its users.
Operator Overloading**
Definition:
The operator overloading feature of C++ is one of the methods of realizing polymorphism.
Giving special meaning to an operator is known as operator overloading.
Operators can have Different behavior at different instances.
Operator overloading is one of the way to achieve compile time polymorphism.
Syntax:
returntype operator operatorsymbol (arglist)
{
//operator function
}
Meaning
Example
increment
++i;
decrement
--i;
unary
minus(negage)
-i;
int x;
unary(int x1)
{
x=x1;
}
void operator-()
// operator overloading
{
x=-x;
}
void display()
{
cout<<x<<endl;
}
};
int main()
{
unary ob(10);
ob.display();
-ob;
ob.display();
}
Output:
10
-10
Meaning
Example
Addition
o3=o1+o2;
Subtraction
o3=o1+o2;
Multiplication
o3=o1*o2;
Division
o3=o1/o2;
Assignment
o2=o1;
Output:
5.5+i2.5
1.5+i5.5
7.0+i8.0
Meaning
Example
Assignment
o2=o1;
+=
Compound
Assignment
o1+=o2;
-=
Compound
Assignment
o1-=o2;
Output:
2+j3
4+j5
6+j8
Overloading Streams**
Class type variables cannot be read or display using cin or cout. By overloading << and >>
operators we can read or display objects or class type variables using cin or cout objects.
<< operator takes ostream as one of the argument and >> operator takes istream as argument.
Syntax:
friend istream & operator>>(istream &, classname &);
friend ostream & operator<<(ostream &,classname &);
Example:
#include<iostream.h>
#include<conio.h>
class complex
{
float real,imag;
public:
complex()
{
real=imag=0;
}
complex(int x,int y)
{
real=x;
imag=y;
}
friend istream & operator>>(istream &in,complex &c)
// Overloading Extraction
operator
{
cout<<"Enter real and imag values:"<<endl;
in>>c.real>>c.imag;
}
friend ostream & operator<<(ostream &out,complex &c)
// Overloading Insertion
operator
{
out<<c.real<<"+j"<<c.imag;
}
};
Output:
int main()
{
Enter real and imag values:
complex c1;
35
cin>>c1;
3+j5
cout<<c1;
}
Type Conversion*
To convert one type of variable into another type, type conversions are used. C automatically
converts one basic type to another basic type. For example, when we assign one float value to integer
variable, it truncates the fractional part and stores the whole number in integer variable.
But to convert class type variables, operator overloading functions are used.
Conversion between Objects and Basic types
Three types of data conversion exits they are,
Conversion from basic type to class type
Conversion from class type to basic type
Conversion from one class type to another class type.
Conversion from basic type to class type
This type used to convert int, char, float type into class type. To convert basic type to class type
constructors are used. These constructors take relevant basic type data as argument.
10
C++ allows us to define an overload casting operator that should be used to convert a class type
data to a basic type.
Constructors do not supports class type to basic type conversion.
The general form of an overloaded casting operator function usually referred to as a conversion
function is,
Syntax:
operator typename
{
//function body
}
11
public:
void get()
{
cout<<"Enter a number:";
cin>>n;
}
operator int()
// To convert class type to int type
{
sum=0;
for(i=0;i<=n;i++)
sum=sum+i;
return sum;
}
};
int main()
{
sum_of_n s;
int ans;
s.get();
ans=s;
cout<<ans;
}
Output:
Enter a number:10
55
// ans-int type, s-class type. // invokes operator int() function.
Explicit Constructor
12
Definition:
Explicit constructor is a constructor when it is invoked, a temporary object will be created and it is
initialized with the provided value, then a copy of temporary object is copied to actual object.
Explanation and Syntax:
A constructor that takes a single argument is, by default, an implicit conversion operator that
converts its argument to an object of its class. In order to avoid such implicit conversion, a constructor that
takes one argument can be declared explicit.
class classname
{
public:
explicit classname(oneargument)
{
-----}
}
Example program for Explicit constructor
#include<iostream.h>
class student
{
private:
char* name;
public:
explicit student(char* temp)
{
name=temp;
cout<<"Name="<<name;
}
};
int main()
{
student ob=student("xxx");
// Invoking explicit constructor
}
Practice Exercises:
1. Complex number addition.
#include<iostream.h>
#include<conio.h>
class complex
{
float real,imag;
public:
complex()
//default constructor
{
real=0.0;
imag=0.0;
}
void get()
{
cout<<"Enter the real value:";
cin>>real;
cout<<"Enter the imag value:";
13
Output:
Name=xxx
cin>>imag;
}
void disp()
{
cout<<real<<"+j"<<imag;
}
friend complex operator+(complex,complex);
};
complex operator+(complex c1,complex c2) //Operator Overloading
{
complex c3;
c3.real=c1.real+c2.real;
c3.imag=c1.imag+c2.imag;
return c3;
}
void main()
{
complex c1,c2,c3;
clrscr();
cout<<"\n\nFirst complex No:\n\n";
c1.get();
cout<<"\n\nSecond complex No:\n\n";
c2.get();
c3=c1+c2;
cout<<"\n\n\nAdded Value:\n\n";
c3.disp();
getch();
}
OUTPUT:
First complex No:
Enter the real value:12
Enter the imag value:3
Second complex No:
Enter the real value:2
Enter the imag value:3
Added Value:
14+j6
2. Create a class Number with a data member value as pointer data type. Overload the new and
delete operator to allocate and de-allocate memory for its memory. Equip a C++ program to get
and display the value of number object.
#include<iostream.h>
class number
{
int *n;
public:
number(int *x)
{
n=x;
cout<<"The given number is:"<<*n<<endl;
}
void *operator new(size_t size)
{
void *p=malloc(size);
return p;
}
void operator delete(void *p)
{
free(p);
cout<<"Object memory deallocated";
}
};
int main()
14
{
int *n=new int;
int x=3;
n=&x;
number *obj=new number(n);
delete(obj);
// dynamic allocation
// dynamic allocation
// de-allocation
}
3. Matrix class using dynamic memory allocation.
#include<iostream.h>
#include<conio.h>
class matrix
{
int **p;
int d1,d2;
public:
matrix(){}
matrix(int x,int y);
void get(int i,int j,int value)
{
p[i][j]=value;
}
int &put(int i,int j)
{
return p[i][j];
}
~matrix()
{
cout<<"\n\nMatrix object destroyed...";
}
matrix operator=(matrix&);
};
matrix matrix::operator=(matrix &m1)
{
int i,j;
matrix m2;
for(i=0;i<m1.d1;i++)
for(j=0;j<m1.d2;j++)
{
m2.get(i,j,m1.put(i,j));
cout<<" "<<m2.put(i,j);
}
return m2;
}
matrix::matrix(int x,int y)
{
d1=x;
d2=y;
p=new int *[d1];
//Dynamic memory allocation
for(int i=0;i<d1;i++)
p[i]=new int[d2];
}
int main()
{
int m,n;
cout<<"\nEnter size of matrix:";
15
Output
The given number is:3
Object memory deallocated
cin>>m>>n;
matrix m1(m,n),m2(m,n);
cout<<"\nEnter the matrix elements row by row:";
int i,j,value;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>value;
m1.get(i,j,value);
}
cout<<"\nFirst matrix:";
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cout<<m1.put(i,j)<<" ";
}
cout<<"\n\n\nCopy constructor invoked....";
cout<<"\nCopied matrix:";
m2=m1;
getch();
}
4. Create a class Student with regno, name, CS1201, CS1202, CS1203 as data members. Overload
the stream operator to get and display the student details. Include a member function to find the
total and publish the result.
#include<iostream.h>
class student
{
int regno;
char name[20];
int cs1201,cs1202,cs1203;
public:
student(){}
friend istream & operator>>(istream &in,student &s)
// Overloading Extraction operator
{
cout<<"Enter Regno,Name and 3 Marks:"<<endl;
in>>s.regno>>s.name>>s.cs1201>>s.cs1202>>s.cs1203;
}
friend ostream & operator<<(ostream &out,student &s)
// Overloading Insertion operator
{
char *status;
if(s.cs1201>50 and s.cs1202>50 and s.cs1203>50)
status="Pass";
else
status="Fail";
out<<"\nName:"<<s.name<<"\nRegno:"<<s.regno<<"\nStatus:"<<status;
}
};
int main()
{
student s;
cin>>s;
cout<<s;
}
5. Write a program to overload new and delete operators to manipulate objects of student class.
The student class must contain data members such as char *name, int rollno, char* branch etc.
The overload new and delete operators must allocate memory for the student class object and its
data members
16
#include<iostream.h>
class student
{
int rollno;
char *name;
char *branch;
public:
student(int rno,char *name1,char *br)
{
rollno=rno;
name=name1;
branch=br;
}
void *operator new(size_t size)
{
void *p=malloc(size);
return p;
}
void operator delete(void *p)
{
free(p);
cout<<"Object memory deallocated";
}
void display()
{
cout<<"Name:"<<name<<"\nRollNo:"<<rollno<<"\nBranch:"<<branch<<endl;
}
};
int main()
{
student *obj=new student(101,"James","IT");
obj->display();
delete(obj);
// de-allocation
}
// dynamic allocation
6. Create a class Complex with real and imag as data member. Use stream operator overloading to
read and print the member values. Write a main method to demonstrate the Complex class.
#include<iostream.h>
#include<conio.h>
class complex
{
int real,imag;
public:
complex()
{
real=imag=0;
}
complex(int x,int y)
{
real=x;
imag=y;
}
17
void display()
{
cout<<real<<"+j"<<imag<<endl;
}
void operator +=(complex c)
{
real=real+c.real;
imag=imag+c.imag;
}
};
int main()
{
Output:
complex c1(2,3),c2(4,5);
2+j3
c1.display();
4+j5
c2.display();
6+j8
c1+=c2;
// Invoking overloaded binary operator +=
c1.display();
}
7. Write a C++ program to perform from complex number to integer by overloading an operator
#include<iostream.h>
class complex
{
int real,imag;
public:
void get()
{
cout<<"Enter real and imag values:";
cin>>real>>imag;
}
operator int()
// To convert class type to int type
{
return(real+imag);
}
};
int main()
{
complex c;
int x;
c.get();
x=c;
cout<<"Converted ineger is:"<<x;
}
8. Write a C++ program to perform from complex number to double by overloading an operator
#include<iostream.h>
class complex
{
double real,imag;
public:
void get()
{
cout<<"Enter real and imag values:";
cin>>real>>imag;
}
operator double()
// To convert class type to int type
{
18
return(real+imag);
}
};
int main()
{
complex c;
double x;
c.get();
x=c;
cout<<"Converted ineger is:"<<x;
}
Output:
Enter real and imag values:
3.4
2.4
Converted ineger is:5.8
Output
The given number is:3
Object memory deallocated
10. Write a C++ program to perform complex number subtraction by overloading an operator
using friend function
#include<iostream.h>
#include<conio.h>
class complex
{
float real,imag;
public:
complex()
{
real=0.0;
imag=0.0;
}
void get()
//default constructor
19
{
cout<<"Enter the real value:";
cin>>real;
cout<<"Enter the imag value:";
cin>>imag;
}
void disp()
{
cout<<real<<"+j"<<imag;
}
friend complex operator-complex,complex);
};
complex operator-(complex c1,complex c2) //Operator Overloading
{
complex c3;
c3.real=c1.real-c2.real;
c3.imag=c1.imag-c2.imag;
return c3;
}
void main()
{
complex c1,c2,c3;
clrscr();
cout<<"\n\nFirst complex No:\n\n";
c1.get();
cout<<"\n\nSecond complex No:\n\n";
c2.get();
c3=c1-c2;
cout<<"\n\n\nAdded Value:\n\n";
c3.disp();
getch();
}
11. Write a C++ program to reverse the given number and assign it to a variable by overloading
the appropriate operator.
#include<iostream.h>
class rev
{
int n;
public:
void get()
{
cout<<"Enter a number:";
cin>>n;
}
void operator+()
{
int i,r,s;
s=0;
i=n;
while(n>0)
{
r=n%10;
s=s*10+r;
n=n/10;
}
20
Part A
1. What is the difference between a parameter and an argument? (Nov/dec 2011)
Parameters
A parameter represents a value that the procedure expects you to pass when you call
it. The procedure's declaration defines its parameters.
When you define a Function or Sub procedure, you specify a parameter list in
parentheses immediately following the procedure name. For each parameter, you specify a
name, a data type, and a passing mechanism (ByVal or ByRef). You can also indicate that a
parameter is optional, meaning the calling code does not have to pass a value for it.
The name of each parameter serves as a local variable within the procedure. You use
the parameter name the same way you use any other variable.
Arguments
An argument represents the value you pass to a procedure parameter when you call
the procedure. The calling code supplies the arguments when it calls the procedure.
When you call a Function or Sub procedure, you include an argument list in
parentheses immediately following the procedure name. Each argument corresponds to the
parameter in the same position in the list.
In contrast to parameter definition, arguments do not have names. Each argument is
an expression, which can contain zero or more variables, constants, and literals. The data type
of the evaluated expression should normally match the data type defined for the
corresponding parameter, and in any case it must be convertable to the parameter type.
2. Explain the purpose of a function parameter. (Nov/dec 2011)
The Function prototype serves the following purposes
1) It tells the return type of the data that the function will return.
2) It tells the number of arguments passed to the function.
3) It tells the data types of the each of the passed arguments.
4) Also it tells the order in which the arguments are passed to the function.
Therefore essentially, function prototype specifies the input/output interface to
the function i.e. what to give to the function and what to expect from the function.
3. Explain the multiple meanings of the operators and in C++ and their
precedence. (Nov/dec 2011)
Precedence Operator Description Associativity
<< Bitwise left shift Left-to-right
>> Bitwise right shift
21
22
23
Binary
operators
+
Meaning
Example
Addition
o3=o1+o2;
Subtraction
o3=o1+o2;
Multiplication
o3=o1*o2;
Division
o3=o1/o2;
Assignment
o2=o1;
24
25