Вы находитесь на странице: 1из 25

CS2203-OBJECT ORIENTED PROGRAMMING

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
{

CS2203-OBJECT ORIENTED PROGRAMMING

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

Multiple Constructors in a class:


One class can have more than one constructor with different number or different types of arguments. During
function call, based on argument type and count they can be invoked. Multiple constructors in a single class is also
called as overloaded constructor.
Example:
#include<iostream.h>
#include<conio.h>
class complex
{
int real,imag;
public:
complex()
// constructor 1-default constructor(0 arguments)

CS2203-OBJECT ORIENTED PROGRAMMING

{
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

Constructor with Friend function and void returntype:


Program to add two complex numbers:
#include<iostream.h>
#include<conio.h>
class complex
{
float real,imag;
public:
complex()
{
real=0;
imag=0;
}
complex(float x,float y)
{
real=x;
imag=y;
}
friend void add(complex c1,complex c2);
};
void add(complex c1,complex c2)
{
cout<<"Sum="<<(c1.real+c2.real)<<"+j"<<(c1.i
mag+c2.imag)<<endl;
}
int main()
{
complex c1;
complex c2(3,5);
add(c1,c2);
complex c3(3,4),c4(7,9);
add(c3,c4);
}

#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;
}

Friend function with class type as return type

CS2203-OBJECT ORIENTED PROGRAMMING

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
}

Constructor with dynamic allocation


4

CS2203-OBJECT ORIENTED PROGRAMMING

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.

Example program for Constructors with dynamic allocation


#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()
{
int *n=new int;
// dynamic allocation
int x=3;
n=&x;
number *obj=new number(n);
// dynamic allocation
delete(obj);
// de-allocation
}

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
}
};

CS2203-OBJECT ORIENTED PROGRAMMING

A Destructor has the following characteristics


A class cannot have more than one destructor.

A destructor must be declared in the public section of a class so that it is accessible to all its users.

It has no return type and takes no arguments.

Cannot be declared as const, volatile or static,

Can be declared virtual or pure virtual.

Example program for Destructors


#include<iostream.h>
#include<conio.h>
class des
{
static int count;
public:
des()
{
count++;
cout<<"Number of object created"<<count<<endl;
}
~des()
{
cout<<"Number of object destroyed"<<count<<endl;
}
};
Output:
int des::count;
Enter Main
int main()
Number of object created1
{
Number of object created2
cout<<"Enter Main"<<endl;
Number of object destroyed2
des ob1,ob2;
Number of object destroyed2
}

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
}

The following Operators cannot be overloaded


Size of operator(sizeof)
Scope resolution operator(::)
Conditional operator(?:)
Class member access operator(. , .* , ->* )

CS2203-OBJECT ORIENTED PROGRAMMING

Pointer to member declarator(::*)


Operators cannot be overloaded in Operator Friend Function are,
Assignment operator(=)
Function call operator (( ))
Subscripting operator([ ])
Class member access operator(->)
Rules for overloading operators:
1. Only existing operators can be overloaded.
2. New operators cannot be created.
3. Overloaded operator must have at least one operand
4. We cannot change the basic meaning of an operator.
5. They cannot be overridden.
6. Unary operator overloaded functions takes no explicit argument and returns no explicit values.
7. Binary arithmetic operators such as +,-,* and / must explicitly return a value.
Operator overloading can be represented as following ways

Unary operator overloading


Binary operator overloading

Unary Operator Overloading:**


The operator operates on only one operand is called as unary operator overloading. For example,
increment, decrement operators etc.
Unary
operators
++
--

Meaning

Example

increment

++i;

decrement

--i;

unary
minus(negage)

-i;

Characteristics of Unary operator function:

Unary operators can be defined as member function or friend function.


If it is defined as member function, then it wont take arguments.
If it is defined as friend function, then it takes one argument

Example program for unary operator overloading


#include<iostream.h>
class unary
{
private:
public:

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

CS2203-OBJECT ORIENTED PROGRAMMING

Binary operator overloading**


The operator operates on two operands are called binary operator overloading. Minus(-) operand
can be used for both unary and binary operator overloading. If it operates on two operands, called binary
operator overloading.
Syntax:
destination_operand=src_operand1 operator src_operand2;
Binary
operators
+

Meaning

Example

Addition

o3=o1+o2;

Subtraction

o3=o1+o2;

Multiplication

o3=o1*o2;

Division

o3=o1/o2;

Assignment

o2=o1;

Characteristics of Binary Operator function:

Binary Operators can be defined as member function or friend function.


If it is defined as member function, then it takes one argument.
If it is defined as friend function, then it takes two arguments.
Example program for binary operator overloading:
#include<iostream.h>
class complex
{
float real, imag;
public:
complex()
{
real=0.0;
imag=0.0;
}
complex(float a,float b)
{
real=a;
imag=b;
}
void display()
{
cout<<"\n"<<real<<"+i"<<imag<<"\n";
}
friend complex operator +(complex c1,complex c2);
};
complex operator +(complex c1,complex c2)
{
complex c3;
c3.real=c1.real+c2.real;
c3.imag=c1.imag+c2.imag;
return(c3);
}
void main()
{
complex c1(5.5,2.5);
complex c2(1.5,5.5);
complex c3;
c3=c1+c2;
c1.display();
c2.display();
c3.display();
}

Output:
5.5+i2.5
1.5+i5.5
7.0+i8.0

CS2203-OBJECT ORIENTED PROGRAMMING

Assignment Operator Overloading**


Definition:
Assignment operator is a binary operator, it can be overloaded only through member function. So
that assignment operator overloaded function takes only one argument.
It is impossible to overload assignment operator using friend function.
Syntax:
destination_operand=src_operand1;
Binary
operators

Meaning

Example

Assignment

o2=o1;

+=

Compound
Assignment

o1+=o2;

-=

Compound
Assignment

o1-=o2;

Example program for overloading the assignment operator


#include<iostream.h>
#include<conio.h>
class complex
{
private:
int real,imag;
public:
complex()
{
real=imag=0;
}
complex(int x,int y)
{
real=x;
imag=y;
}
void display()
{
cout<<real<<"+j"<<imag<<endl;
}
void operator +=(complex c)
{
real=real+c.real;
imag=imag+c.imag;
}
};
int main()
{
complex c1(2,3),c2(4,5);
c1.display();
c2.display();
c1+=c2;
// Invoking overloaded binary operator +=
c1.display();
}

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.

CS2203-OBJECT ORIENTED PROGRAMMING

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

CS2203-OBJECT ORIENTED PROGRAMMING

Example program for Conversion from basic type to class type


#include<iostream.h>
class time_ex
{
int hrs,mins;
public:
time_ex()
{
hrs=0;
mins=0;
}
time_ex(int t)
// This function supports basic type to class type conversion
{
hrs=t/60;
mins=t%60;
}
void display()
{
cout<<"Time="<<hrs<<":"<<mins<<endl;
}
};
int main()
Output:
{
Time=0:0
int x=134;
Time=2:4
time_ex t1;
Time=2:14
t1.display();
time_ex t2(124);
t2.display();
time_ex t3;
t3=x;
//t3-class type x-int type //basic type to class type conversion
t3.display();
}
Conversion from class type to basic type

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
}

The casting operator function should satisfy the following conditions:


It must be a class member.
It must not specify a return type.
It must not have any arguments.
Example program for Conversion from class type to basic type
#include<iostream.h>
class sum_of_n
{
int n,i,sum;

11

CS2203-OBJECT ORIENTED PROGRAMMING

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.

Conversion from one class type to another class type


To convert one class type object into another class type or to assign one class type object values into
another class type object, this conversion method is used. Conversions between objects of different classes
can be carried out by either a constructor or a conversion function.
Example program for Conversion from one class type to another class type
#include<iostream.h>
#include<conio.h>
#include<iostream.h>
class pow_2
{
public:
int n;
pow_2(int x)
{
n=x;
cout<<n<<" Power 2="<<n*n<<endl;
}
};
class pow_3
{
public:
pow_3(pow_2 obj)
{
cout<<obj.n<<" Power 3="<<obj.n*obj.n*obj.n<<endl;
}
Output:
};
3 Power 2=9
int main()
3 Power 3=27
{
pow_2 obj1(3);
pow_3 obj2(obj1);
// invokes conversion constructor(obj1 & obj2 belongs to two different
classes)
}

Explicit Constructor
12

CS2203-OBJECT ORIENTED PROGRAMMING

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

CS2203-OBJECT ORIENTED PROGRAMMING

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

CS2203-OBJECT ORIENTED PROGRAMMING

{
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

CS2203-OBJECT ORIENTED PROGRAMMING

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

CS2203-OBJECT ORIENTED PROGRAMMING

#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

CS2203-OBJECT ORIENTED PROGRAMMING

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

CS2203-OBJECT ORIENTED PROGRAMMING

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

9. Write a C++ program for overloading new and delete operators.


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()
{
int *n=new int;
// dynamic allocation
int x=3;
n=&x;
number *obj=new number(n);
// dynamic allocation
delete(obj);
// de-allocation
}

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

CS2203-OBJECT ORIENTED PROGRAMMING

{
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

CS2203-OBJECT ORIENTED PROGRAMMING

cout<<"Reversed number is:"<<s;


}
};
int main()
{
rev r;
r.get();
+r;
}

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

4. What is a copy constructor? (Nov/dec 2011)


A copy constructor is used to declare and initialize an object from another object. It
takes a reference to anobject of the same class as an argument
Eg: integer i2(i1);
would define the object i2 at the same time initialize it to the values of i1.
Another form of this statement is
Eg: integer i2=i1;
The process of initializing through a copy constructor is known as copy initialization .

21

CS2203-OBJECT ORIENTED PROGRAMMING


5. What is type conversion?
Conversion from basic data type to class type can be done in destination class. Using
constructors does it. Constructor takes a single argument whose type is to be converted.
Eg: Converting int type to class type
class time
{
int hrs,mins;
public:
Time ( int t) //constructor
{
hours= t/60 ; //t in minutes
mins =t % 60;
}
};
Constructor will be called automatically while creating objects so that this conversion is
done automatically.
6. Explain the functions of default constructor.
The constructor with no arguments is called default constructor
Eg:
Class integer
{
int m,n;
Public:
Integer( );
};
integer::integer( )//default constructor
{
m=0;n=0;
}
void main()
{
integer I;
cout<<i.m<<i.n;
}
the statement
integer a;
invokes the default constructor
7. What is the need for overloading the assignment operator?
The assignment operator is used to copy the values from one object to another
already existing
object. Consider the following example:
Student s1(5); // calls constructor
Student s2; // calls default constructor
S2=s1;// calls Cents assignment operator
The statement s2=s1 invokes overloaded assignment operator function. If that function
is not implemented by the user, compiler itself defines that.
8. Write any four special properties of constructor.
T hey should be declared in the public section
They are invoked automatically when the objects are created
They do not have return types, not even void and therefore, and they cannot return
values
They cannot be inherited, though a derived class can call the base class
They can have default arguments
Constructors cannot be virtual f unction
9. List any four operators that cannot be overloaded.
Class member access operator (. , .*)
Scope resolution operator (::)

22

CS2203-OBJECT ORIENTED PROGRAMMING

Size operator ( sizeof )


Conditional operator (?:)

10. What is function objects?


Objects of the classes can be created with () operator. In this case objects can be
written with a () and can be treated like functions. Such objects can be called like a function,
and are known as function objects.
11. Write the difference between realloc() and free()
Existing block(ie, already allocated by malloc() function) can be freed(ie, deallocated)
by free() function.
To change the block size of the memory which was allocated, realloc() function is used.
12. Give the purpose of gets and puts function.
gets()

char * gets ( char * str );


- which is used to get string from stdin(ie, console) until a newline
character(\n\) or the End-of-File is reached.
puts()
int puts ( const char * str );
- to write string to stdout(ie, at console) and appends a newline character at the
end.
13. Define constructor?
A function with the same name as the class itself responsible for construction and
returning objects of the class is called constructor.
14. What is parameterized constructor?
A constructor with one or more than one argument is called parameterized constructor.
Ex
Class complex
{
int r,I;
Public:
Complex complex( int real, int imag)
{
r=real;
i=imag;
}
};
Whenever the above complex function is invoked that assigns the r and I value as per
the values passed in the argument of the object while creation.
Complex c(2,3); // Which sets r as 2 and I as 3.
15. Define destructor?
The function which preceded by ~ is called as destructor. The desctructors
automatically called when the object goes out of scope. Destructors used to delete objects
and its members at the end of the execution.
16. What do you mean by explicit constructor?
Calling the constructors explicitly is known as explicit constructors.
Syntax:
Classname objectname=classname(argument list);
Example:
Complex c=complex(2,3);
17. Explain multiple constructor?
A class with more than one constructor is known as multiple constructor. Multiple
constructor is constructed with constructor name as class name and with different argument
list. That is either with empty default constructor or with parameterized constructor.
18. What is operator overloading?
The process of giving additional meaning to the operator by overloading it, is called as

23

CS2203-OBJECT ORIENTED PROGRAMMING


operator overloading.
Example:
Using + operator to add two strings.
The process of giving an existing operator a new , additional meaning is called operator
overloading.
19. Give Example for Binary operators.

Binary
operators
+

Meaning

Example

Addition

o3=o1+o2;

Subtraction

o3=o1+o2;

Multiplication

o3=o1*o2;

Division

o3=o1/o2;

Assignment

o2=o1;

20. What is the lifetime of an object?


The life time of a global object is throughout the execution of the program. Otherwise ,
the object comes
into existence when constructor is over and is alive till it gives out of scope, i.e just before the
destructor is applied.
21. Define new operator?
The operator new is used for allocation of memory, it gets memory from heap. It is
similar to malloc() in C.
Example : to get memory for an integer and assign the address of allocated memory to
pointer p,
Int* p = new int.
22. Define delete operator?
Delete in C++ does a similar job as free() function in C, i.e it releases the memory
occupied by the new
operator.
23. Define wrapper classes?
A class which makes a C like struct or built in type data represented as a class. For
example, an Integer
wrapper class represents a data type int as a class.
24. List out the operators that can not be overloaded as a friend?
1. Assignment operator =.
2.Function call operator ()
3.Array subscript operator []
4. Access to class member using pointer to object operator ->.
25. Define type conversion?
When we need to convert between different types , we guide the compiler how to
convert from one type to
another by writing operator functions or constructors.
Various types are,
1. Basic type to class type conversion
2. Class type to basic type conversion
3. One class type to another class type conversion
26. Difference between unary and binary operator?
All operators having a single argument are unary operators. When we overload these
operators as member function, we do not need to pass any argument explicitly. Operators with
two argument are known as binary operators. They will have a single argument when defined
as member function. The first argument to that operator is always the invoking object.
27. Explain insertion and extraction operator?

24

CS2203-OBJECT ORIENTED PROGRAMMING


Insertion operator : The << operator which is used to write to the console is known as
insertion operator. It
is also known as the output operator.
Extraction operator : The >> operator which is used to read from the keyboard is
known as extraction
operator. It is also known as the input operator.
28. Explain function overloading?
Function overloading in C++ allows more than one function with same name but with
different set of
arguments. This process is known as function overloading and each participating function is
known as
overloaded function.
29. List out the user defined conversion?
1.conversion from built in data type to an object.
2. conversion from object to a built in data type.

25

Вам также может понравиться