You are on page 1of 65

Department of Computer Engineering OOPC (2140705)

INDEX
Sr. Title Pg. Start Complete Sign Marks
No. No. Date Date
1 Illustrate the use of Input
Operator and Output Operator.
2 Illustrate the concept of
Reference Variable, Default
Arguments and Inline
Functions.
3 Implement the concept of
Arrays and Function
Overloading.
4 Implement the concept of Class.
5 Implement the concept of
Constructor & Friend Function.
6 Implement the concept of
Inheritance.
7 Implement the concept of
Operator Overloading and type
conversion.
8 Implement the concept of Run-
time Polymorphism (Virtual
Function).
9 Implement the concept of File
Management.
10 Implement the concept of
Exception Handling and
Templates.

Alpha College of Engineering and TechnologyPage 1


Department of Computer Engineering OOPC (2140705)

Practical-1
AIM: Illustrate the use of Input Operator and Output Operator
through C++ programs
C++ uses a convenient abstraction called streams to perform input and output
operations in sequential media such as the screen, the keyboard or a file.

A stream is an entity where a program can either insert or extract characters to/from.
There is no need to know details about the media associated to the stream or any of
its internal specifications. All we need to know is that streams are a
source/destination of characters, and that these characters are provided/accepted
sequentially.
stream description
cin standard input stream
cout standard output stream

Standard output (cout)

1. The standard output by default is the screen, and the C++ stream object defined to
access it is cout. The cout is used together with the insertion operator, which is
written as <<.
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the value of x on screen
2. Multiple insertion operations (<<) may be chained in a single statement:
cout << "This " << " is a " << "single C++ statement";

Alpha College of Engineering and TechnologyPage 2


Department of Computer Engineering OOPC (2140705)

Output:
This is a single C++ statement.
3. To insert a line break, a new-line character shall be inserted at the exact position
the line should be broken. In C++, a new-line character can be specified as \n (i.e., a
backslash character followed by a lowercase n). For example:
cout << "First sentence.\n";
cout << "Second sentence.\nThird sentence.";
Output:
First sentence.
Second sentence.
Third sentence.

4. The endl manipulator can also be used to break lines. For example:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
Output:
First sentence.
Second sentence.
The endl manipulator produces a newline character, exactly as the insertion of '\n'
does.
Standard input (cin)

1. The standard input by default is the keyboard, and the C++ stream object
defined to access it is cin. For formatted input operations, cin is used
together with the extraction operator, which is written as >>. This
operator is then followed by the variable where the extracted data is
stored. For example:
int age;
cin >> age;

Alpha College of Engineering and TechnologyPage 3


Department of Computer Engineering OOPC (2140705)

The first statement declares a variable of type int called age, and the second extracts
from cin a value to be stored in it. This operation makes the program wait for input
from cin; generally, this means that the program will wait for the user to enter some
sequence with the keyboard.
// Example
#include <iostream.h>
int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}
Output:
Please enter an integer value: 2
The value you entered is 2 and its double is 4.
2. Extractions on cin can also be chained to request more than one datum in a single
statement:
cin >> a >> b;
3. The extraction operator can be used on cin to get strings of characters
in the same way as with fundamental data types and thus extracting a string
means to always extract a single word, not a phrase or an entire sentence:
string mystring;
cin >> mystring;
To get an entire line from cin, there exists a function, called getline that takes the
stream (cin) as first argument, and the string variable as second.
// Example
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}
Output:

Alpha College of Engineering and TechnologyPage 4


Department of Computer Engineering OOPC (2140705)

What's your name? Homer Simpson


Hello Homer Simpson.
What is your favorite team? The Isotopes
I like The Isotopes too!

Program-1: Write a program to print your name, enrollment number, branch and
semester using cin, cout and endl.
Program & Output:

Alpha College of Engineering and TechnologyPage 5


Department of Computer Engineering OOPC (2140705)

Example: A program to calculating the area and perimeter of rectangle.


#include<iostream.h>
int main()
{
int width,height,area,perimeter;
cout<<"Enter Width of Rectangle = ";
cin>>width;
cout<<"Enter Height of Rectangle = ";
cin>>height;
area=height*width;
cout<<"Area of Rectangle ="<<area<<endl;
perimeter=2*(height+width);
cout<<" Perimeter of rectangle are = "<<perimeter<<endl;
return 0;
}
Output:
Enter Width of Rectangle=2
Enter Height of Rectangle=2
Area of Rectangle=4
Perimeter of rectangle are=8

Program-2: Write a program to calculate the simple interest S as given input of P,


R & T.
Program & Output:

Alpha College of Engineering and TechnologyPage 6


Department of Computer Engineering OOPC (2140705)

Program-3: Write a program to check whether the given input number is prime or
not.
Program & Output:

Alpha College of Engineering and TechnologyPage 7


Department of Computer Engineering OOPC (2140705)

Practical-2
AIM: Illustrate the concept of Reference Variable, Default Arguments
and Inline Functions through C++ programs.
Reference Variable:
When you create an independent reference, all you are creating is another name for an object.
All independent references must be initialized when they are created. The reason for this is
easy to understand. Aside from initialization, you cannot change what object reference
variable points to. Therefore, it must be initialized when it is declared.

The definition of a reference in C++ is such that it does not need to exist. It can be
implemented as a new name for an existing object.
Example:
#include <iostream.h>
int main ()
{
// declare simple variables
int i;
double d;
// declare reference variables
int &r = i;
double & s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
Output:

Alpha College of Engineering and TechnologyPage 8


Department of Computer Engineering OOPC (2140705)

Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
Default Arguments:
In C++ programming, you can provide default values for function parameters. The
idea behind default argument is very simple. If a function is called by passing
argument/s, those arguments are used by the function. But if all argument/s are not
passed while invoking a function then, the default value passed to arguments are
used. Default value/s are passed to argument/s in function prototype. Working of
default argument is demonstrated in the figure below:

Inline Functions:
C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled
because compiler would need to replace all the code once again otherwise it will continue
with old functionality.
To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.

Alpha College of Engineering and TechnologyPage 9


Department of Computer Engineering OOPC (2140705)

A function definition in a class definition is an inline function definition, even without the use
of the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers:
#include <iostream.h>
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
int main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
Output:
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

Program-4: Write a program in C++ to implement default arguments.


Program & Output:

Alpha College of Engineering and TechnologyPage 10


Department of Computer Engineering OOPC (2140705)

Program-5: Write a program to calculate the area of a triangle using inline


functions.
Program & Output:

Alpha College of Engineering and TechnologyPage 11


Department of Computer Engineering OOPC (2140705)

Program-6: Write a program to swap the values of two integer variables using pass
by reference value using functions.
Program & Output:

Practical-3
AIM: Implement the concept of Arrays and Function Overloading
through C++ program.
Function Overloading:
C++ allows you to specify more than one definition for a function name in the same
scope, which is called function overloading.
An overloaded declaration is a declaration that had been declared with the same
name as a previously declared declaration in the same scope, except that both

Alpha College of Engineering and TechnologyPage 12


Department of Computer Engineering OOPC (2140705)

declarations have different arguments and obviously different definition


(implementation).
When you call an overloaded function, the compiler determines the most
appropriate definition to use by comparing the argument types you used to call the
function or operator with the parameter types specified in the definitions. The
process of selecting the most appropriate overloaded function or operator is called
overload resolution.

#include <iostream>
/* Function arguments are of different data type */
long add(long, long);
float add(float, float);
int main()
{
long a, b, x;
float c, d, y;
cout << "Enter two integers\n";
cin >> a >> b;
x = add(a, b);
cout << "Sum of integers: " << x << endl;
cout << "Enter two floating point numbers\n";
cin >> c >> d;
y = add(c, d);
cout << "Sum of floats: " << y << endl;
return 0;
}
long add(long x, long y)
{
long sum;
sum = x + y;

Alpha College of Engineering and TechnologyPage 13


Department of Computer Engineering OOPC (2140705)

return sum;
}
float add(float x, float y)
{
float sum;
sum = x + y;
return sum;
}

Array:
C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
To declare an array in C++, the programmer specifies the type of the elements and
the number of elements required by an array as follows:

type arrayName [ arraySize ];


Example:
#include <iostream.h>
#include <iomanip.h>
int main ()
{
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ )
{
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;
// output each array element's value
for ( int j = 0; j < 10; j++ )
{
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
// use of setw() function to format the output
}
return 0;
}
Output:
Element Value
0 100
1 101
2 102
3 103
4 104
5 105

Alpha College of Engineering and TechnologyPage 14


Department of Computer Engineering OOPC (2140705)

6 106
7 107
8 108
9 109

Program-7: Write a program in C++ and implement the function overloading.


Write overloaded swap function to swap two integers, two characters and two
floats.
Program & Output:

Alpha College of Engineering and TechnologyPage 15


Department of Computer Engineering OOPC (2140705)

Program-8: Write a program in C++ and implement the function overloading.


Write overloaded volume function to find the volume of square box, rectangle box
and cone.
Program & Output:

Alpha College of Engineering and TechnologyPage 16


Department of Computer Engineering OOPC (2140705)

Program-9: Write a function in C++, which accepts an integer array and its size as
arguments and swap the elements of every even location with its following odd
location.
Program & Output:

Alpha College of Engineering and TechnologyPage 17


Department of Computer Engineering OOPC (2140705)

Practical-4
AIM: Implement the concept of Class through C++ program.
Class:
Classes are created using the keyword class. A class declaration defines a new type
that links code and data. This new type is then used to declare objects of that class.
Thus, a class is a logical abstraction, but an object has physical existence. In other
words, an object is an instance of a class.

class class-name {
private data and functions
access-specifier:
data and functions
access-specifier:
data and functions
// ...
access-specifier:
data and functions
} object-list;

Example:
class smallobj //define a class
{
private:
int somedata; //class data
public:
void setdata(int d) //member function to set data
{
somedata = d;
}
void showdata() //member function to display data

Alpha College of Engineering and TechnologyPage 18


Department of Computer Engineering OOPC (2140705)

{
cout << \nData is << somedata; }
};

The object-list is optional. If present, it declares objects of the class. Here, access-
specifier is one of these three C++ keywords:
1. public
2. private
3. protected
By default, functions and data declared within a class are private to that class
and may be accessed only by other members of the class.
The public access specifier allows functions or data to be accessible to other
parts of your program.
The protected access specifier is needed only when inheritance is
involved.

Class Data
The smallobj class contains one data item: somedata, which is of type int. The data
items within a class are called data members (or sometimes member data). There
can be any number of data members in a class. The data member somedata follows
the keyword private, so it can be accessed from within the class, but not from
outside.
Member Functions
Member functions are functions that are included within a class. There are two
member functions in smallobj: setdata() and showdata(), they follow the keyword
public, they can be accessed from outside the class.

Example:
#include <iostream.h>

Alpha College of Engineering and TechnologyPage 19


Department of Computer Engineering OOPC (2140705)

////////////////////////////////////////////////////////////////
class Distance
{
private:
int feet;
float inches;
public:
void setdist(int ft, float in) //set Distance to args
{ feet = ft; inches = in; }
void getdist() //get length from user
{
cout << \nEnter feet: ; cin >> feet;
cout << Enter inches: ; cin >> inches;
}
void showdist() //display distance
{ cout << feet << \- << inches << \; }
};
////////////////////////////////////////////////////////////////
int main()
{
Distance dist1, dist2; //define two lengths
dist1.setdist(11, 6.25); //set dist1
dist2.getdist(); //get dist2 from user
//display lengths
cout << \ndist1 = ; dist1.showdist();
cout << \ndist2 = ; dist2.showdist();
cout << endl;
return 0;
}

Output:

Enter feet: 10
Enter inches: 4.75
dist1 = 11-6.25
dist2 = 10-4.75
Static Data Members:
A data member is created and initialized only once, in contrast to non-static data
members who are created again and again for each separate object of the class. Static
data members are created when the program starts. The static data member is a data
member that is shared by all the objects of a class. Only one copy of static data
member is kept in memory, they are not dependent on object initialization. Static
keyword can be used with following:
1. Static variable in functions
2. Static data members
3. Static member functions

Alpha College of Engineering and TechnologyPage 20


Department of Computer Engineering OOPC (2140705)

Example:
#include<iostream.h>
class X
{
static int i;
};
int X::i=1;
int main()
{
X obj;
cout<< obj.i; //prints the value of i.
}
Static variable inside functions:
Static variables when used inside the function are initialized only once, and then
they hold their value even through function calls. These are stored on static storage
area.
Example:
#include<iostream.h>
void counter()
{
static int count=0;
cout<<count++;
}
int main()
{
for(int i=0;i<5;i++)
{
counter(); // 0 1 2 3 4
}}
Static Member Functions:
Static member functions are considered to have class scope. In contrast to non-static
member functions, these functions have no implicit this argument; therefore, they
can use only static data members, enumerators, or nested types directly. Static
member functions can be accessed without using an object of the corresponding class
type. It can be called using an object and the direct member access, operator. But, its
more typical to call a static member function by itself, using class name and scope
resolution :: operator.

Example:
// static_member_functions.cpp
#include <stdio.h>

class StaticTest
{
private:

Alpha College of Engineering and TechnologyPage 21


Department of Computer Engineering OOPC (2140705)

static int x;
public:
static int count()
{
return x;
}
};
int StaticTest::x = 9;

int main()
{
printf_s("%d\n", StaticTest::count()); // 9
}

Program-10: Write a program in C++, Create a class Box with length, breadth and
height as data members and Box1 as class object. Write a program to read and
display the volume of box with formula: length * height * breadth.
Program & Output:

Alpha College of Engineering and TechnologyPage 22


Department of Computer Engineering OOPC (2140705)

Program-11: Write a program in C++, Create a class Student with no, name and
percentage as data members and Getdata and Putdata as member functions. Write
a program to read and display the details of 3 students using array of objects.
Program & Output:

Alpha College of Engineering and TechnologyPage 23


Department of Computer Engineering OOPC (2140705)

Program-12: Write a program in C++, to implement static data members and static
member function concept.
Program & Output:

Alpha College of Engineering and TechnologyPage 24


Department of Computer Engineering OOPC (2140705)

Practical-5
AIM: Implement the concept of Constructor & Friend Function
through C++ program.
Constructor:
A class constructor is a special member function of a class that is executed whenever
we create new objects of that class. A constructor will have exact same name as the
class and it does not have any return type at all, not even void.
Example:
#include <iostream.h>
class Line
{
public:
Line(); // This is the constructor
};
// Member functions definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << endl;

Alpha College of Engineering and TechnologyPage 25


Department of Computer Engineering OOPC (2140705)

}
// Main function for the program
int main( )
{
Line line;
return 0;
}

Output:
Object is being created

Parameterized Constructor:
A default constructor does not have any parameter, but if you need, a constructor
can have parameters.
Example:
#include <iostream.h>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor

private:
double length;
};

// Member functions definitions including constructor


Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}

void Line::setLength( double len )


{
length = len;
}

double Line::getLength( void )


{
return length;
}
// Main function for the program
int main( )
{
Line line(10.0);
// get initially set length.

Alpha College of Engineering and TechnologyPage 26


Department of Computer Engineering OOPC (2140705)

cout << "Length of line : " << line.getLength();


return 0;
}

Output:
Object is being created, length = 10
Length of line : 10

Destructor:
A destructor is a special member function of a class that is executed whenever an
object of its class goes out of scope or whenever the delete expression is applied to a
pointer to the object of that class. A destructor will have exact same name as the class
prefixed with a tilde (~) and it can neither return a value nor can it take any
parameters. Destructor can be very useful for releasing resources before coming out
of the program like closing files, releasing memories etc.
Example:
#include <iostream.h>
class myclass {
public:
int who;
myclass(int id);
~myclass();
};
myclass::myclass(int id)
{
cout << "Initializing " << id << "\n";
who = id;
}
myclass::~myclass()
{
cout << "Destructing " << who << "\n";
}
int main()
{
myclass local_ob1(3);
cout << "This will not be first line displayed.\n";
myclass local_ob2(4);
return 0;
}

Output:
Initializing 1
Initializing 2
Initializing 3
This will not be first line displayed.

Alpha College of Engineering and TechnologyPage 27


Department of Computer Engineering OOPC (2140705)

Initializing 4
Destructing 4
Destructing 3
Destructing 2
Destructing 1

Friend Functions:
It is possible to grant a nonmember function access to the private members of a class
by using a friend. A friend function has access to all private and protected members
of the class for which it is a friend. To declare a friend function, include its prototype
within the class, preceding it with the keyword friend.
Consider this program:
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
friend int sum(myclass x);
void set_ab(int i, int j);
};
void myclass::set_ab(int i, int j)
{
a = i;
b = j;
}
// Note: sum() is not a member function of any class.
int sum(myclass x)
{
/* Because sum() is a friend of myclass, it can
directly access a and b. */
return x.a + x.b;
}
int main()
{
myclass n;
n.set_ab(3, 4);
cout << sum(n);
return 0;
}
In this example, the sum( ) function is not a member of myclass. However, it still has
full access to its private members. Also, notice that sum( ) is called without the use of
the dot operator. Because it is not a member function, it does not need to be qualified
with an object's name. Although there is nothing gained by making sum( ) a friend
rather than a member function of myclass, there are some circumstances in which
friend functions are quite valuable.

Alpha College of Engineering and TechnologyPage 28


Department of Computer Engineering OOPC (2140705)

First, friends can be useful when you are overloading certain types of
operators.
Second, friend functions make the creation of some types of I/O functions
easier.
The third reason that friend functions may be desirable is that in some cases,
two or more classes may contain members that are interrelated relative to
other parts of your program.

Program-13: Create a class called time with hh, mm and ss as integer data
members. One constructor should initialize this data to 0, and another should
initialize it to fixed values. A member function should display it, in 11:59:50
format. Provide a sum function to add two time objects. Write main() to
demonstrate it.
Program & Output:

Alpha College of Engineering and TechnologyPage 29


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 30


Department of Computer Engineering OOPC (2140705)

Program-14: Create a class called time with hh, mm and ss as integer data
members. One constructor should initialize this data to 0, and another should
initialize it to fixed values. A member function should display it, in 11:59:50
format. Provide a friend function to add two time objects. Write main() to
demonstrate it.
Program & Output:

Alpha College of Engineering and TechnologyPage 31


Department of Computer Engineering OOPC (2140705)

Practical-6
AIM: Implement the concept of Inheritance through C++ program.
Inheritance:
Inheritance allows us to define a class in terms of another class, which makes
it easier to create and maintain an application. This also provides an
opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called the base
class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example,
mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and
so on.
Forms of Inheritance:
Single Inheritance: One base class and one super class.
Multiple Inheritance: Multiple base class and one sub class.
Hierarchical Inheritance: One base class and multiple sub class.

Alpha College of Engineering and TechnologyPage 32


Department of Computer Engineering OOPC (2140705)

Multi-level Inheritance: A subclass inherits from a class that itself inherits


from another class.
Hybrid Inheritance: A subclass inherits from multiple base classes and all of
its base classes inherit from a single base class.

Base & Derived Classes:


A class can be derived from more than one classes, which means it can inherit data
and functions from multiple base classes. To define a derived class, we use a class
derivation list to specify the base class(es). A class derivation list names one or more
base classes and has the form:
class derived-class : access-specifier base-class
Example: Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream>
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;

Alpha College of Engineering and TechnologyPage 33


Department of Computer Engineering OOPC (2140705)

Output:
Total area: 35

Access Control and Inheritance:


A derived class can access all the non-private members of its base class. Thus base-
class members that should not be accessible to the member functions of derived
classes should be declared private in the base class.
Access public protected private
Same class yes yes yes
Derived
yes yes no
classes
Outside
yes no no
classes

We can summarize the different access types according to who can access them in
the following way:
A derived class inherits all base class methods with the following exceptions:
Constructors, destructors and copy constructors of the base class.
Overloaded operators of the base class.
The friend functions of the base class.

Multiple Inheritance:
A C++ class can inherit members from more than one class and here is the extended
syntax:
class derived-class : access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every
base class and they will be separated by comma.
Example:
class Student
{
int Rollno;
char SName[20];
float Marks1;
protected:

Alpha College of Engineering and TechnologyPage 34


Department of Computer Engineering OOPC (2140705)

void Result();
public:
Student();
void Enroll();
void Display();
};
class Teacher
{
long TCode;
char TName[20];
protected:
float Sal
ary;
public:
Teacher ();
void Enter();
void Show();
};
class Course:public Student,private Teacher
{
long CCode[10]
char CourseName[50];
char StartDate[8],EndDate[8];
public:
Course();
void Commence();
void CDetail();
};

Program-15: Write a C++ to implement Single Inheritance.


Program & Output:

Alpha College of Engineering and TechnologyPage 35


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 36


Department of Computer Engineering OOPC (2140705)

Program-16: Write a C++ to implement Multiple Inheritance.


Program & Output:

Alpha College of Engineering and TechnologyPage 37


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 38


Department of Computer Engineering OOPC (2140705)

Program-17: Write a C++ to implement Hybrid Inheritance.


Program & Output:

Alpha College of Engineering and TechnologyPage 39


Department of Computer Engineering OOPC (2140705)

Practical-7
AIM: Implement the concept of Operator Overloading and type
conversion through C++ program.
Operator Overloading:
It is an important technique that has enhanced the power of extensibility of c+
+.
The mechanism to provide special meanings to an operator is known as
operator overloading. i.e. operator works with user defined data types with same
syntax as they works with basic data types.
It provides a flexible option for the creation of new definition for most of the
c++ operators.
Although the semantics of an operator can be extended, we cannot change its
syntax, the grammatical rules that govern its use such as the number of operands,
precedence and associativity.
When an operator is overloaded, its original meaning is not lost.
Defining Operator Overloading:
To overload an operator, a special function, called operator function is used
with following form:
Return_type classname :: operatorop(arglist)
{
Function body
}
Return_type is the type of value returned by the function, op is the operator
being overloaded. The op is preceded by the keyword operator. Operatorop is
the function name.
Operator functions must be either
Member functions(non-static)
Friend functions

Alpha College of Engineering and TechnologyPage 40


Department of Computer Engineering OOPC (2140705)

Friend function will have one argument for unary operators and two for
binary operators, while a member function has no arguments for unary operators
and one 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, this is not the case with friend function.
friend vector operator-(vector);
friend vector operator+(vector, vector);
vector operator-();
vector operator+(vector);
vector is a data type of class.
The process of overloading involves the following steps:
1. Creates a class that defines the data type that is to be used in the overloading
operations.
2. Declare the operator function operatorop() in the public part of the class. It
may be either a member function or a friend function.
3. Define the operator function to implement the required operations.
Overloaded operators functions can be invoked by expressions such as
op x or x op for unary operators
x op y for binary operators
op x(or x op) would be interpreted as operator op (x) for friend functions.
x op y would be interpreted as either
x.operator op(y) for member functions, or
operator op(x,y) for friend functions.

Alpha College of Engineering and TechnologyPage 41


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 42


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 43


Department of Computer Engineering OOPC (2140705)

Following are the three types of data conversion between incompatible types.
1) Conversion from basic type to class type.
2) Conversion between class type to basic type.
3) Conversion between one class to another class type.
a. Conversion routine in source object : operator function.
b. Conversion routine in destination object: constructor function.

Alpha College of Engineering and TechnologyPage 44


Department of Computer Engineering OOPC (2140705)

Program-18: Create Distance class with feet, inches as data members. Overload +
operator to add two Distance objects. Write a program to test this class.
Program & Output:

Alpha College of Engineering and TechnologyPage 45


Department of Computer Engineering OOPC (2140705)

Program-19: Create Distance class with feet, inches as data members. Overload <
operator to compare two Distance objects(use friend function). Write a program to
test this class.
Program & Output:

Alpha College of Engineering and TechnologyPage 46


Department of Computer Engineering OOPC (2140705)

Program-20: Define two classes Time24 and Time12. Use conversion routines to
convert time in Time24 to time in Time12. Write a program to test it.

Alpha College of Engineering and TechnologyPage 47


Department of Computer Engineering OOPC (2140705)

Program & Output:

Alpha College of Engineering and TechnologyPage 48


Department of Computer Engineering OOPC (2140705)

Practical-8
AIM: Implement the concept of Run-time Polymorphism(Virtual
Function ) through C++ program.
Virtual Function:
A virtual function is a member function that is declared within a base class
and redefined by a derived class. To create virtual function, precede the
functions declaration in the base class with the keyword virtual. When a class
containing virtual function is inherited, the derived class redefines the virtual
function to suit its own needs.
Base class pointer can point to derived class object. In this case, using base
class pointer if we call some function which is in both classes, then base class
function is invoked. But if we want to invoke derived class function using
base class pointer, it can be achieved by defining the function as virtual in
base class, this is how virtual functions support runtime polymorphism.

/* Example to demonstrate the working of virtual function in C++ programming. */

#include <iostream.h>
class B
{
public:
virtual void display() /* Virtual function */
{ cout<<"Content of base class.\n"; }
};
class D1 : public B
{
public:
void display()
{ cout<<"Content of first derived class.\n"; }
};
class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived class.\n"; }
};
int main()

Alpha College of Engineering and TechnologyPage 49


Department of Computer Engineering OOPC (2140705)

{
B *b;
D1 d1;
D2 d2;

/* b->display(); // You cannot use this code here because the function of base class is
virtual. */

b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */
return 0;
}
Output:
Content of first derived class.
Content of second derived class.
Program-21: Implement C++ program to demonstrate Run-time
Polymorphism(Virtual Function). Create class shape with area as member
function and derive class circle, rectangle and triangle from shape having area as
member function to calculate area of circle, rectangle and triangle.
Program & Output:

Alpha College of Engineering and TechnologyPage 50


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 51


Department of Computer Engineering OOPC (2140705)

Practical-9
AIM: Implement the concept of File Management through C++
program.
Files:
To read and write from a file, this requires another standard C++ library called
fstream, which defines three new data types:

Data Type Description


This data type represents the output file stream and is used
ofstream
to create files and to write information to files.
This data type represents the input file stream and is used
ifstream
to read information from files.
This data type represents the file stream generally, and has
the capabilities of both ofstream and ifstream which means
fstream
it can create files, write information to files, and read
information from files.

Opening a File:
A file must be opened before you can read from it or write to it. Both the
ofstream or fstream object may be used to open a file for writing and ifstream
object is used to open a file for reading purpose only. Following is the
standard syntax for open() function, which is a member of fstream, ifstream,
and ofstream objects. void open(const char *filename, ios::openmode mode).
Here, the first argument specifies the name and location of the file to be
opened and the second argument of the open() member function defines the
mode in which the file should be opened.
Mode Flag Description
ios::app Append mode. All output to that file to be appended to the end.

Alpha College of Engineering and TechnologyPage 52


Department of Computer Engineering OOPC (2140705)

Open a file for output and move the read/write control to the end of the
ios::ate
file.
ios::in Open a file for reading.
ios::out Open a file for writing.
If the file already exists, its contents will be truncated before opening
ios::trunc
the file.
You can combine two or more of these values by ORing them together. For example
if you want to open a file in write mode and want to truncate it in case it already
exists, following will be the syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File
When a C++ program terminates it automatically closes flushes all the streams,
release all the allocated memory and close all the opened files. But it is always a
good practice that a programmer should close all the opened files before program
termination. Following is the standard syntax for close() function, which is a member
of fstream, ifstream, and ofstream objects.
void close();

Writing to a File:
While doing C++ programming, you write information to a file from your program
using the stream insertion operator (<<) just as you use that operator to output
information to the screen. The only difference is that you use an ofstream or fstream
object instead of the cout object.

Reading from a File:


You read information from a file into your program using the stream extraction
operator (>>) just as you use that operator to input information from the keyboard.
The only difference is that you use an ifstream or fstream object instead of the cin
object.
Program-22: Write a C++ program to Read and Write characters or integers from
file.

Alpha College of Engineering and TechnologyPage 53


Department of Computer Engineering OOPC (2140705)

Program & Output:

Alpha College of Engineering and TechnologyPage 54


Department of Computer Engineering OOPC (2140705)

Program-23: Write a C++ program to Read and Write class objects from file.
Program & Output:

Alpha College of Engineering and TechnologyPage 55


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 56


Department of Computer Engineering OOPC (2140705)

Practical-10
AIM: Implement the concept of Exception Handling and Templates
through C++ program.
Exception Handling:
An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
throw: A program throws an exception when a problem shows up. This is
done using a throw keyword.
catch: A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The catch
keyword indicates the catching of an exception.
try: A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.
Syntax:
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}

Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throw statements.
The operand of the throw statements determines a type for the exception and can be
any expression and the type of the result of the expression determines the type of
exception thrown.

Alpha College of Engineering and TechnologyPage 57


Department of Computer Engineering OOPC (2140705)

Following is an example of throwing an exception when dividing by zero condition


occurs:
/ using standard exceptions
#include <iostream>
#include <exception>
using namespace std;

class myexception: public exception


{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;

int main () {
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << '\n';
}
return 0;
}

Output:
My exception happened.

Templates:
Templates are the foundation of generic programming, which involves
writing code in a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function.
The library containers like iterators and algorithms are examples of generic
programming and have been developed using template concept.
There is a single definition of each container, such as vector, but we can define
many different kinds of vectors for example, vector <int> or vector <string>.

Function Template:
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}

Alpha College of Engineering and TechnologyPage 58


Department of Computer Engineering OOPC (2140705)

Here, type is a placeholder name for a data type used by the function. This name can
be used within the function definition.
Example of a function template that returns the maximum of two values:
#include <iostream>
#include <string>

using namespace std;

template <typename T>


inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{

int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;

double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;

string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;

return 0;
}

Output:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World

Program-24: Write a program in C++ that handle division by zero exception.


Program & Output:

Alpha College of Engineering and TechnologyPage 59


Department of Computer Engineering OOPC (2140705)

Program-25: Write a program in C++ to implement function template.


Program:

Alpha College of Engineering and TechnologyPage 60


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 61


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 62


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 63


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 64


Department of Computer Engineering OOPC (2140705)

Alpha College of Engineering and TechnologyPage 65

You might also like