0% found this document useful (0 votes)
11 views37 pages

Unit-3 CC

The document outlines the syllabus for a Programming with C++ course, focusing on classes, objects, constructors, destructors, operator overloading, and type conversions. It explains the structure of classes, access specifiers, member functions, and the use of arrays within classes, as well as memory allocation for objects and static data members. Additionally, it covers advanced topics such as friend functions, const member functions, and pointers to member functions.

Uploaded by

PRIYADHARSHINI K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views37 pages

Unit-3 CC

The document outlines the syllabus for a Programming with C++ course, focusing on classes, objects, constructors, destructors, operator overloading, and type conversions. It explains the structure of classes, access specifiers, member functions, and the use of arrays within classes, as well as memory allocation for objects and static data members. Additionally, it covers advanced topics such as friend functions, const member functions, and pointers to member functions.

Uploaded by

PRIYADHARSHINI K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

DEPARTMENT OF B.

COM IT

COURSE CONTENT

CLASS:II B.COM IT

SUBJECT : PROGRAMMING WITH C++

Syllabus
Unit - III

Classes and object – Constructors and Destructors – Operator overloading – Type


conversions
Class and Objects:
CLASS:

 A class is a way to bind data and associated function together.


 A class is an expanded concept of a data structure, instead of holding only data , it
can hold both data and function.
 The data is to be hidden from external use.
 Classes are generally declared using the keyword class, with
the following format:

class class_name
{
private:
variable declaration;
public:
function declaration;

};

• The body of the declaration can contain members that can be either data or
function declaration, and optionally access specifier.
• The variable declared inside the class is known as data member and function
are known as member functions.
• Access specifier are keyword in object oriented language that set the
accessibility of classes, method and other member.
• Access specifier is one of the following keyword: public, private, protected
• These specifier modify the access rights that the member following
• them acquire:
o private members of class are accessible only from within other member
of same class or from their friends.
o protected members are accessible form members of their same class
and from their friends but also from members of their derived classes.
o public members are accessible from anywhere the object is visible.
• By default, all members of class declared with the class keyword have private
access for all its member. Therefore, any member that is declared before one
other class specifier automatically has private access.
• Only member function can have access to private data member and private
function of that data.

OBJECT:

• Once a class has been created, we can create variable of that type(class type)
by using following syntax which is called object.
• we can create any number of objects belonging to that class by declaring more
than one object in one statement. This statement are written in main().
• The objects can also be defined by placing their name immediately after the
closing brace of the class.

Accessing class member:


• A object can be declared in the main(),and member functions are declared in
class in public section so always a member function can be called by using
object.

Syntax:
object_name.member_function(arguments);
Ex:
s.getdata();

• A data member can also be access by using object only , if data member is
declared as public.
• If data member is declared private then you cannot access it by using object
directly in object

Defining Member Function:

• A member function can be defined in two places in the class:


1. inside the class definition
2. outside the class definition

1) Inside the class definition:


• To write a member function inside the class instead of only
declaration(prototype).

2) Outside the class definition:

• To write function we need to declare function inside the class and


definition(function body) is written outside the class.
• The general form of a member function definition:

return_type
class_name::function_name(arument)
{
function body
}

• The membership label class_name :: tells the compiler that the function
function_Name belongs to the class class_name.
• :: is scope resolution operator.

Making an Outsdide Function Inline:

• We can define a member function outside and still make it inline by just using the
qualifier inline in the header line of function definition.
Nesting Member Function:

• A member function can be called by using its name inside another member
function the same class is called nesting member function.

• Ex:

#include<iostream>
using namespace std;
class number
{
private:
int a,b,s1,s2;
public:
int getdata(int m,int n);
int sum();
int sub();
int show()
{
cout<<"\n Enter number1: ";
cin>>a;
cout<<"\n Enter number2: "; cin>>b;
cout<<"\n Answer of Addition:"<<sum()<<endl; cout<<"\n Answer of
Addition:"<<sub()<<endl;
}
};
int number::getdata(int m,int n)
{
a=m; b=n;
}
int number::sum()
{
s1=a+b; return(s1);
}
int number :: sub()
{
s2=a-b; return(s2);
}
int main()
{
number x; x.getdata(10,20); x.show();
return 0;
}

Private Member Function:

• Generally we declare , data members are in private section and member


function in public section, that’s why we call a member function from main()
through object.
• But if we declare a member function in private section then we can not call
directly from the main(), because it’s private function.
• To call private function , we have to create public function of that class and we
call this private function inside that public function , then the public function
called by object from main().
• Ex:

#include<iostream> using namespace std;


class value
{
private:
int a,b;
void getdata();
public:
void show();
};
void value::getdata()
{
cout<<"Enter number1: "; cin>>a;
cout<<"Enter number2: "; cin>>b;
}
void value::show()
{
getdata();
cout<<"Two numbers are "<<a <<"\n"<<b;
}
int main()
{
value v; v.show(); return 0;
}

Array within Class:

• The arrays can be used as member variable in a class.


• An array is collection of same data type or group of data item that store in a
common name.

• Ex:
#include<iostream>
using namespace std;
class average
{
private:
int n,A[20];
public:
void getdata()
{
cout<<"Number of element: "; cin>>n;
cout<<"Enter the data in array:\n "; for(int i=0;i<n;i++)
{
cout<<"A["<<i<<"]";
cin>>A[i];
}
}
float avg()
{
float sum=0,ans; for(int i=0;i<n;i++) sum=sum+A[i]; ans=sum/n;
cout<<"Average is: "<<ans;

}
};
int main()
{
average a; a.getdata();
a.avg();
return 0;
Memory allocation for object:

• The memory space for objects are allocated when they are declared , not when
the class is specified.
• For member function , when member function are created it will occupy the
memory space only once when they are defining in a class.
• So all objects created for that class can use same member functions , so no
separate space is allocated for member functions when the object are created.
• For data member , only space for data members is allocated separately for each
object when is created.
• The separate space allocation for data member is essential because the data
member will hold different data values for different objects.
• For example, a class student have three data members such as reg_no, age,
per and two member functions getdata() and show().
• If we create three object S1 ,S2, S3 then, object S1 takes up space for: reg_no ,
age , per object S2 takes up space for: reg_no , age , per object S3 takes up
space for: reg_no , age , per
• But it will access common member function getdata() and show(), so it will take
up space only one time when class is created.

Static Data Member:


• Static variable are normally used to maintain values common to the entire class.
• For example, a static data member can be used as a counter that record
occurrences of all the objects.
• A static member variable has certain characteristic:
1. It automatically initialized zero when the first object is created , no other
initialization is permitted. Where a simple variable have initially garbage
value.
2. Only one copy of that member is created for entire class and shared by all
objects of that class, no matter how many objects are created.
3. It is visible only within a class, but its life time is the entire program.
• Ex:
#include<iostream>
using namespace std;
class student{
char name[15];
float age;
public:
void getdata(); void putdata();
};
void student :: getdata()
{
cout<<"Enter Name: "; cin>>name; cout<<"Enter Age: "; cin>>age;
}
void student :: putdata()
{
cout<<"Name: "<<name<<"\n"; cout<<"Age: "<<age <<"\n";
}
const int size=2; int main()
{
student s[size]; // array of object for(int i=0;i<size;i++)
{
cout<<"Detail of student"<<i+1<<"\n";
s[i].getdata();
}
cout<<"\n";
for(int i=0;i<size;i++)
{
cout<<"\n\nStudent"<<i+1<<"\n";
cout<<"--------\n"; s[i].putdata();
}
return 0;
}
Object as Function Argument:

• Like any other data type, an object may be used as a


function argument. This can be done in two way:
1. A copy of the entire object is passed to the function, which is called call
by value.
2. Only the address of the object is transferred to the function, which is
called call/pass by reference.
• Ex:
#include<iostream>
using namespace std;
class Square{ int x; public:
void getdata(int m)
{
x=m;
}
int answer(Square s)
{
x=s.x*s.x;
}
void show()
{
cout<<"Answer is:"<<x;
}
};
int main()
{
Square s1,s2;
s1.getdata(6);
s2.answer(s1);
s2.show();
return 0;
}

Returning objects:

• A function can not only receive objects as arguments but also can return them.
• Like:
#include<iostream>
using namespace std;
class SUM
{
int x;
public:
void getdata(int m)
{
x=m;
}
SUM sum(SUM s)
{
SUM temp;
temp.x=x+s.x;
return(temp);
}
void show()
{
cout<<"Answer is: "<<x;
}
};
int main()
{
SUM s1 ,s2,s3;
s1.getdata(4);
s2.getdata(10);
s3=s1.sum(s2);
s3.show();
return 0;
}

Friendly Functions:

• Due to ‘data hiding ’ feature of c++, the private data members of class can not
be access outside the class. So a function which are not member of the class,
they can not be access the private data of that class.
• In c++, there is facility available to access private data of class even if it is not
member function of that class. It is possible bye using friend function.
• As the name suggests, the function acts as a friend to a class. As a friend of a
class, it can access its private and protected members.
• To make an outside function “friendly” to class, declare the function as friend of
that class.
• The friend functions are declared by using friend keyword.

Syntax:
friend return_type function_name(arg_list);

• Generally arguments in friend functions are object type. because of outside the
class a data member can not directly access, so a object can access it.
• A function can be declared as friend for any number of class. It can not be
member function of any class. It have full rights to access private data of the
class.
• Advantage of having friend function:
1. We can able to access the other class members in our class, if we use
friend keyword.
2. We can access the members without inheriting the class.
• Disadvantage:
1. Maximum size of memory will occupied by object
according to the size of friend member.
2. Break the concept of ‘data hiding’ in oop.
• Characteristic of friend function:
1. It is not in the scope of the class which it has been declared as friend.
2. It can not be called using the object of that class. It can be invoked like a
normal function without the help of object.
3. It can not access data member directly, it must be use object with dot(.)
operator and data member.
4. Normally it has object as argument.
• Ex:
#include<iostream>
using namespace std;
class MEAN{ int n1,n2; public:
void getdata()
{
cout<<"Enter num1: "; cin>>n1; cout<<"Enter num2: "; cin>>n2;
}
friend float ans(MEAN m);
};
float ans(MEAN m)
{
return float(m.n1+m.n2)/2;
}
int main()
{
MEAN m1;
m1.getdata();
cout<<"Answer is: "<<ans(m1); return 0;
}

Const member function:

• Function member can made constant by writing word const keyword between
header of the function and body.

• Constant member function means it can not modify the object.

• Normally function member which are not supposed to modify the object should
be made constant so that there are no chance that accidently function member
modifies the object.
Pointer to Member:

• Just like pointer to normal variable and function , we can have pointer to class
member function and member variable.

syntax for declare pointer data member: • Ex


data_type class_name::*pointer_name; int A ::* p;

• You can initialize p like this also:

syntax: • Ex:
data_type class_name::*pointer_name=&class_name::data_member int A::*p=&A::m;

• Likewise, you can access the data member through


a pointer to a class.

• Pointer to member functions are one of the c++’s rarely used features, while
they do not have widely applicability, some time member function pointer are
useful to solve certain problems.
• Member function pointer can not be dereferenced directly by themselves .they
must be called on behalf of some object.
• To declare a pointer to member function you give the prototype of function it can
point to,as before but the name of this function is replaced by a construction that
scopes the pointer – you give it the name of the class whose member function it
can point to.

Syntax:
return_type (class_name::*pointer_name)(argument_list)
• You dereference a member function pointer by using .* or ->*, supplying a
reference or pointer to an object on the left, as appropriate , and the function
pointer on the right.
• Note that member function does not have the same data type as nonmember
function that has the same number and type of argument and the same return
type.
• Ex.
#include<iostream> using namespace std;
class test{ public: int a;
void fun(int b)
{
cout<<"The value of b is: "<<b<<endl;
}
};
int main()
{
int test::*p=&test::a; // pointer to data member declaration
void(test::*p1)(int)=&test::fun; // pointer to function declaration
test T;
T.*p=10;
cout<<"The value of a is:"<<T.*p<<endl; (T.*p1)(20);
}

Constructors and Destructors:


Constructors:
• we know that the objects are allocated memory per instance basis when they are
created. But the question is that who will allocate memory to object at the time of
creation?.
• The c++ provides solution of these problem is constructor, which enables an
object initialize itself when it is created.
• For example, if we create object student s1 then the compiler automatically
supplies the constructor known as default constructor as follows:

student
{
}

Characteristic of constructor:

 Its name is same as class name.


 It has no arguments
 Its does not have any return type.
 Body part is null(no statement in body).
 It is called automatically when object is created.
 They should be declare in public section.
• Default constructor is constructor that takes no arguments. The default
constructor for class student has form student::student().
• A constructor which has all default arguments, for example student::student( int
x=0) is also default constructor, since it can be called with no argument.
• Ex:
#include<iostream>
using namespace std;
class point{
int x,y;
public:
point() //default constructor
{
}
void set_point()
{
x=0; y=0;
}
void set_point(int x1,int y1)
{
x=x1; y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2;
p1.set_point();
p2.set_point(1,2);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P1 is = ";
p2.put_point();
return 0; }

• In above program, we have written default constructor that is exactly same as the
compiler provide.
• We can write initialization statement in body part of default constructor which is
allowed.
• For that constructor first create the object by allocating memory and then execute
statements in body of constructor, if provided.
• If we provide the initialization statements in body of constructor, the object gets
initialized by default values provided in body at the time of creating object as
constructor.
• for Ex:
point() // default constructor with initialization
{
X=0; Y=0;
}

Parameterized constructor:

• The default constructor are used initialize the object with default values.
• But all objects are not initialized to same values rather different object needs
to be initialized by different values.
• To initialize object with different values, we use function like getvalue().
• C++ provides feature is parameterize constructor to solve this problem.
• The constructor that can take arguments are called parameterize
constructor .
• The advantage of using parameterize constructor that we can pass the
value at the time of defining object with which the compiler automatically calls
it
• Ex
#include<iostream>
using namespace std;
class point
{
int x,y;
public:
point() //default constructor
{
x=0; y=0;
}
point(int x1,int y1) //parameterized constructor
{
x=x1; y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(3,9); cout<<"point P1 is = "; p1.put_point(); cout<<"point P2 is =
"; p2.put_point();
return 0;
}
Multiple Constructor: (Overloaded Constructor)

• In a class if we use more than one constructor with each constructor are
different, this concept is called constructor overloading.
• Ex:
#include<iostream>
using namespace std;
class point
{
int x,y;
public:
point() //default constructor
{
x=0; y=0;
}
point(int x1) //one parameter constructor
{
x=x1; y=0;
}
point(int x1,int y1) //two parameter constructor
{
x=x1; y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(3),p3(3,4);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
cout<<"point P3 is = ";
p3.put_point();
return 0;
}
Constructor with Default Argument:

• A argument is a value given in the declaration that the compiler automatically


insert if you don’t provide a value in function call.
• It is possible to define constructor with default argument.
• Ex:
#include<iostream>
using namespace std;
class point{
int x,y; public:
point()
{
x=0; y=0;
}
point(int x1,int y1=1)
{
x=x1; y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(3),p3(9);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
cout<<"point P3 is = ";
p3.put_point();
return 0;
}

Dynamic Initialization of Object:

• As variable , object can be also dynamically initialized by values provided


by the users at the run time.
• The parameterized constructor is used for the dynamic
initialization of object at run time.
• Ex:
#include<iostream> using namespace std;
class point{ int x,y; public: point()
{
x=0; y=0;
}
point(int x1,int y1)

{
x=x1; y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2,p3;
cout<<"Enter x1 co-ordinate:";
int m,n;
cin>>m;
cout<<"Enter y1 co-ordinate:";
cin>>n;
p1=point(m,n);
cout<<"Enter x2 co-ordinate:";
cin>>m;
cout<<"Enter y2 co-ordinate:";
cin>>n;
p2=point(m,n);
cout<<"Enter x3 co-ordinate:";
cin>>m;
cout<<"Enter y3 co-ordinate:";
cin>>n;
p3=point(m,n);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
cout<<"point P3 is = ";
p3.put_point();
return 0;
}

Copy Constructor:

• Copy constructor is used to create the new object with


previously created object.
• In other term, copy constructor create a new object as copy of previous
object.
• For example if we create p1 object for point class like, point p1(5,5) ;
• The following statement create p2 with value of p1.point p2(p1);
• The copy of constructorfor any class is written as:

Syntax

class_name(class_name& object)
{
// constructor body
}

• For ex:
point(point& p) //copy constructor
{
x=p.x;
Y=p.y;
}
• Observe that constructor has one argument which is reference to the object
of same class of which the copy constructor is member. Using this reference,
it copies each data member.
• We can call copy constructor in either ways
point p2(p1);
or
point p2=p1;
• Ex
#include<iostream>
using namespace std;
class point{ int x,y; public: point()
{
x=0; y=0;
}
point(int x1,int y1)
{
x=x1; y=y1;
}
point(point& p)
{
x=p.x;
y=p.y;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(1,1);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
point p3(p2);
cout<<"point P3 is = ";
p3.put_point();
point p4(p1);
cout<<"point P4 is = ";
p4.put_point();
return 0;
}

Dynamic Constructor:

• The constructor can also be used to allocate memory while creating objects.
• This will enable the system to allocate the right amount of memory for each
objects when the objects are not of the same size, thus resulting is the
saving memory.
• Allocation of memory to object at the time of their constructor is called
dynamic constructor.
• The memory is allocated with help of new operator.
• By using new operator we get exact amount of memory storage space at run
time which are used in constructor.
• Ex

#include<iostream> #include<string.h>
using namespace std; class String
{
char *name; int length; public:
String()
{
length=0;
name= new char[length+1];
}
String(char *s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
void display()
{
cout<<name<<"\n";
}
};
int main()
{
char *str="Welcome";
String str1(str),str2("BCA");
String str3(str),str4;
str1.display();
str2.display();
str3.display();
return 0;
}

Constructing Two Dimensional Arrays:

#include<iostream>
using namespace std; class matrix
{
int **p; int d1,d2; public:
matrix(int x,int y);
void get_element(int i,int j,int val)
{
p[i][j]=val;
}
int &put_element(int i,int j)
{
return p[i][j];
}
};
matrix:: matrix(int x, int y)
{
d1=x; d2=y;
p= new int *[d1];
for(int i=0;i<d1;i++)
{
p[i]=new int[d2];
}
}
int main()
{
int m,n;
cout<<"Enter size of matrix: "; cin>>m>>n;
matrix A(m,n);
cout<<"Enter matrix Element: "; int i,j,val;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>val; A.get_element(i,j,val);
}
cout<<"\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<" "<<A.put_element(i,j)<<" ";
}
cout<<"\n";
}
cout<<"\n";
cout<<"The value of on position(1,2) is : "<<A.put_element(1,2); cout<<"\n";
return 0;
}
Const Object:

• We may create and use constant object using const keyword before
object declaration.
• For Ex:
const matrix X(m,n);// X is constant
• Any attempt to modify the value of const object will generate compile-time
error.
• A constant object can call only const member function.

Destructors:

• The destructor is used to destroy the object that


have been created by constructor.
• It will destroy the object once the use is over.
• Like constructor, destructor is a member function whose name is same
as class name but it is denoted by tilde (~) sign.
• For Ex:
~ test()
{
}
or
~ test()
{
delete p;
}
• The destructor destroy everything created by the class automatically.
• You do not have to put any delete keyword in it, except if you allocate any
memory with new keyword.
• There Is always only one destructor in entire class .
• The objects are destroy in the reverse order of their creation.

Characteristics of Destructor:

• A destructor never takes any arguments and does not return any value.
• Destructor is having same name as class preceded by tild(~) sign.
• It is called automatically when the scope of object is over.
• Default destructor is provided by compiler, if user does not
• provide.
• Ex:

#include<iostream> using namespace std;


int count=0;
class test
{
public:
test();
~test();
};
test::test()
{
count++;
cout<<count<<" object is created..\n";
}
test::~test()
{
cout<<count<<" object is destroyed..\n";
count--;
}
int main()
{
cout<<"\n";
test a;
{
cout<<"In the inner block \n";
test x,y,z;
}
return 0;
}

Operator Overloading
• Operator overloading is an important concept in C++. It is a type of
polymorphism in which an operator is overloaded to give user defined
meaning to it. Overloaded operator is used to perform operation on user-
defined data type. For example '+' operator can be overloaded to perform
addition on various data types, like for Integer, String(concatenation) etc.
• Almost any operator can be overloaded in C++. However there are few
operator which cannot be overloaded. Operator that are not
overloaded are follows
 scope operator - ::
 sizeof
 member selector - .
 member pointer selector - *
 ternary operator - ?:

Operator Overloading Syntax

Implementing Operator Overloading in C++

• Operator overloading can be done by implementing a function which can


be :

1. Member Function
2. Non-Member Function
3. Friend Function

• Operator overloading function can be a member function if the Left


operand is an Object of that class, but if the Left operand is different, then
Operator overloading function must be a non-member function.
• Operator overloading function can be made friend function if it needs
access to the private and protected members of class.

Restrictions on Operator Overloading in C++


Following are some restrictions to be kept in mind while implementing operator
overloading.

1. Precedence and Associativity of an operator cannot be changed.


2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary,
binary remains binary etc.
3. No new operators can be created, only existing operators can be overloaded.
4. Cannot redefine the meaning of a procedure. You cannot change how integers
are added.

Example Programs on operator Overloading

#include<iostream>
using namespace std;

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Output:
12 + i9

Unary Operators Overloading in C++

• The unary operators operate on a single operand and following are the
examples of Unary operators −
 The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator.
• The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -obj, and
++obj but sometime they can be used as postfix as well like obj++ or obj--.
• Following example explain how minus (-) operator can be overloaded for prefix
as well as postfix usage.

#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};

int main() {
Distance D1(11, 10), D2(-5, 11);
-D1; // apply negation
D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

return 0;
}

Output
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11

Binary Operators Overloading in C++

• The binary operators take two arguments and following are the examples of
Binary operators. You use binary operators very frequently like addition (+)
operator, subtraction (-) operator and division (/) operator.
• Following example explains how addition (+) operator can be overloaded.
Similar way, you can overload subtraction (-) and division (/) operators.
#include <iostream>
using namespace std;

class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

public:

double getVolume(void) {
return length * breadth * height;
}

void setLength( double len ) {


length = len;
}

void setBreadth( double bre ) {


breadth = bre;
}

void setHeight( double hei ) {


height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;

return 0;
}
Output
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Type Conversion
• Type conversion is the process of converting one type into another. In
other words, converting an expression of a given type into another is
called as Type casting.
• There are two ways of achieving the type conversion namely,
 Automatic Conversions otherwise called as Implicit
Conversions
 Type Casting otherwise called as Explicit Conversions

Implicit Conversions:

 Done by the compiler on its own, without any external trigger from the
user.
 Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to
avoid lose of data.
 All the data types of the variables are upgraded to the data type of the
variable with largest data type.
bool -> char -> short int -> int ->

unsigned int -> long -> unsigned ->

long long -> float -> double -> long double


• It is possible for implicit conversions to lose information, signs can be lost
(when signed is implicitly converted to unsigned), and overflow can occur
(when long long is implicitly converted to float).

Example of Type Implicit Conversions:

#include <iostream>
using namespace std;

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}
Output:
x = 107

y=a

z = 108

Explicit Conversions:

• This process is also called type casting and it is user-defined. Here the
user can typecast the result to make it of a particular data type.
• In C++, it can be done by two ways:
1. .Converting by assignment: This is done by explicitly defining the
required type in front of the expression in parenthesis. This can be
also considered as forceful casting.

Syntax

(type) expression
here type indicates the data type to which the final
result is converted.

• Example:

// C++ program to demonstrate


// explicit type casting

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}
Output:
Sum = 2

2. Conversion using Cast operator: A Cast operator is an unary


operator which forces one data type to be converted into another
data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
• Example:
#include <iostream>
using namespace std;
int main()
{
float f = 3.5;

// using cast operator


int b = static_cast<int>(f);

cout << b;
}
Output:
3

Advantages of Type Conversion:


• This is done to take advantage of certain features of type hierarchies or
type representations.
• It helps to compute expressions containing variables of different data
types.

POSSIBLE 5 MARKS

1. Explain the concept of copy constructor with the help of an example program .
[Dec 2012]
2. What is operator overloading ? Briefly explain general rules of operator overloading.
[June 2013]
3. What do you mean by copy constructor ? Explain it with a suitable C++ program. [June
2014]
4. Differentiate between default constructor and parameterized constructor with the help of
an example [June 2015]
5. List the C++ operators that cannot be overloaded. Give reasons for any two of these
explaining why they cannot be overloaded.[June 2016]
6. What do you understand by a Default Constructor ? How is a default constructor
equivalent to a constructor with default arguments ? [ Dec 2017]

POSSIBLE 8 MARKS

1. Write a program in C++, which take two 10 3 x 3 matrices as input and find sum of
them. Implement suitable constructor and destructor for this program. [Dec 2012]
2. Explain need of operator overloading. Also explain why some operators cannot
be overloaded ? Write a C++ program to overload '+' operator to add two
character strings. [Dec 2012]
3. Write C++ program to find factorial of a given number using copy constructor.
[ Dec 2014]
4. What do you mean by operator-overloading ? List the operators which cannot be
overloaded. Write a C++ program for unary minus (-) operator overloading.[June
2015]
5. Write a C++ program to add two complex numbers. In this program you need to
create complex class and define proper constructor for object initialization. [ June
2015]
6. Write a C++ program to create a matrix class. Define constructor and destructor
for this class. Also define a method to find the sum of two matrices. [June 2017]
7. What is the difference between overloading and overriding concepts in C++ ?
Explain the usage of these concepts with suitable example code in C++. [Dec
2017]
8. Write a C++ program to create a Book class. Define constructor and destructor
for this class. Also define the methods to show the title and price of the books.
[Dec 2016]

You might also like