SlideShare a Scribd company logo
SRI RAMAKRISHNA INSTITUTE OF TECHNOLOGY
AN AUTONOMOUS INSTITUTION
COIMBATORE-641010
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
LAB MANUAL
20CSG02 – PROGRAMMING IN C++
LABORATORY
FIRST YEAR – SECOND SEMESTER
(Common to all Branches)
COMPILED BY
PREETHA V M.E., AP/CSE
VIDYA PRIYA DARCINI S M.Tech., AP/CSE
COURSE OBJECTIVE:
This course provides a practical experience on the concepts of Object Oriented
Programming using C++ programming language.
LIST OF EXPERIMENTS:
1. Programs using Objects and Classes
2. Programs using Constructors and Destructors
3. Programs using friend function & friend class.
4. Programs using Function Overloading
5. Programs to overload unary & binary operators as member function & non-member
function
6. Programs using types of inheritance
7. Programs using virtual functions
8. Programs using Function and class templates
9. Programs using Files and Streams
10. Programs using Exception handling
COURSE OUTCOMES:
CO1: Ability to apply the concept related to Classes and Objects in simple programs
CO2: Ability to apply the concepts of polymorphism to achieve enhanced functionalities of
functions and operator.
CO3: Ability to deploy inheritance in simple C++ programs
CO4: Ability to design simple applications that support File Processing
CO5: Ability to develop programs that are capable of handling Exceptions
REFERENCES:
1. Herbert Schildt, “C++ The Complete Reference”, 5th
Edition, Tata McGraw Hill, New
Delhi,
2. Bjarne Stroustrup, “The C++ Programming Language”, 4th Edition, Addison-Wesley,
2013.
3. Deitel and Deitel, “C++ How to Program”, 10th
Edition, Prentice Hall India Learning
Private Limited, 2018.
4. Robert Lafore, “Object Oriented Programming in C++”, 4th
edition, Pearson India,
2002.
5. Stanley B. Lippman and Josee Lajoie, “C++ Primer”, 5th
Edition, Pearson Education,
New Delhi, 2013.
6. E.Balagurusamy, “Object Oriented Programming with C++”, 6th
Edition, Tata McGraw
Hill, 2013.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 1
LIST OF EXPERIMENTS
Sl. No. Description
Marks
Awarded
1 Objects and Classes
2 Constructors and Destructors
3 Friend Function & Friend Class.
4 Function Overloading
5 Operator Overloading
6 Inheritance
7 Virtual functions
8 Function and Class Templates
9 Files and Streams
10 Exception handling
Total Average
Signature of the Course Instructor
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 2
Date:
OBJECTS, CLASSES
Exercise 1
Class:
It is a user defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage
are their properties.
A Class is a user defined data-type which have data members and member functions. Data
members are the data variables and member functions are the functions used to manipulate
these variables and together these data members and member functions defines the
properties and behavior of the objects in a Class. In the above example of class Car, the data
member will be speed limit, mileage etc. and member functions can be apply brakes, increase
speed etc.
Object:
An Object is an instance of a Class. When a class is defined, no memory is allocated
but when it is instantiated (i.e. an object is created) memory is allocated. A class is defined in
C++ using keyword class followed by the name of class. The body of class is defined inside
the curly brackets and terminated by a semicolon at the end.
Fig :1.1 Defining Class and Declaring Objects
Declaring Objects: When a class is defined, only the specification for the object is
defined; no memory or storage is allocated. To use the data and access functions defined
in the class, you need to create objects.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 3
Syntax:
Class_Name Object_Name;
Sample Program:
1. Define a class named Student which includes id, name as Data members and insert(),
display() as the member functions to insert the id and name and display the same
respectively.
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main(void) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
return 0;
}
Output:
201 Sonoo
202 Nakul
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 4
Lab Question:
1. Define a class to represent a bank account which includes the following members as
Data members: a) Name of the depositor b) Account Number c) Amount and the
member functions are a)Withdrawal() c)Deposit() b) Display_Balance().
Extra Question:
1. A class defines a blueprint for an object. We use the same syntax to declare objects of
a class as we use to declare variables of other basic types. For example:
Box box1; // Declares variable box1 of type Box
Box box2; // Declare variable box2 of type Box
Kristen is a contender for valedictorian of her high school. She wants to know how
many students (if any) have scored higher than her in the exams given during this
semester.
Create a class named Student with the following specifications:
• An instance variable named to hold a student's 5 exam scores.
• A void input() function that reads 5 integers and saves them to scores.
• An int calculateTotalScore() function that returns the sum of the student's
scores.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 5
Results:
S.NO DESCRIPTION WEIGHTAGE MARK AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 6
Date:
CONSTRUCTORS AND DESTRUCTOR
Exercise 2
Constructors:
A constructor is a member function of a class which initializes objects of a class. In
C++, Constructor is automatically called when object (instance of class) create. It is special
member function of the class.
A constructor is different from normal member functions in following ways:
• Constructor has same name as the class itself.
• Constructors don’t have return type.
• A constructor is automatically called when an object is created.
• If we do not specify a constructor, C++ compiler generates a default constructor for us
(expects no parameters and has an empty body).
Types of Constructors:
• Default Constructor
• Parameterized Constructor
• Copy Constructor
Default Constructors: Default constructor is the constructor which doesn’t take any
argument.
It has no parameters.
Sample Program:
1. Program to use default constructor for printing two variable values.
#include <iostream>
using namespace std;
class construct
{
public:
int a, b;
construct ()// Default Constructor
{
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 7
a = 10;
b = 20;
}
};
int main ()
{
construct c; // Default constructor called automatically when the object is
created cout << "a: "<< c.a << endl << "b: "<< c.b;
return 1;
}
Output:
10
20
Parameterized Constructors: It is possible to pass arguments to constructors. Typically,
these
arguments help initialize an object when it is created. To create a parameterized constructor,
simply add parameters to it the way you would to any other function. When you define the
constructor’s body, use the parameters to initialize the object.
Sample Program:
1. Program to print two variable values by using parameterized Constructor.
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)// Parameterized Constructor
{
x = x1;
y = y1;
}
int getX()
{
return x;
}
int getY()
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 8
{
return y;
}
};
int main()
{
Point p1(10, 15);// Constructor called
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
// Access values assigned by constructor
return 0;
}
Output:
p1.x=10, p1.y=15
Copy Constructor: A copy constructor is a member function which initializes an object
using another object of the same class. A copy constructor has the following general
function prototype:
Class Name (const ClassName &old_obj);
Sample Program:
1. Program to print two variable values by using Copy Constructor.
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
Point(const Point &p2) // Copy constructor
{
x = p2.x;
y = p2.y;
}
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 9
int getX()
int getY()
{ return x; }
{ return y; }};
int main()
{
Point p1(10, 15); // Normal constructor is
called here Point p2 = p1; // Copy constructor
is called here
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();// Let us access values
assigned by constructors
cout << "np2.x = " << p2.getX() << ", p2.y =
" << p2.getY(); return 0;
}
Output:
p1.x=10, p1.y=15
p2.x=10, p2.y=15
Destructor: Destructor is a member function which destructs or deletes an object.
Destructor is called when:
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called.
Destructors have same name as the class preceded by a tilde (~), destructors don’t take
any argument and don’t return anything.
Sample Program:
1. Program to use Destructor for deleting an object created using Class String.
class String
{
private:
char *s;
int size;
public:
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 10
String(char *); // constructor
~String(); // destructor
};
String::String(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}
String::~String()
{
delete []s;
}
Lab Exercise:
1. Write a C++ program to calculate the area of triangle, rectangle and circle by using
the concepts of default, parameterized and copy constructor. Finally use destructor to
delete the objects created.
Extra Questions:
1. Write a C++ program to create a class FD a/c which contains member (fdno, name,
amt, interest rate, maturity amt & No. of months). Write parameterized constructor
where interest rate should be default argument. Calculate maturity amt using interest
rate & display all the details.
2. Write a C++ program using copy constructor to process Shopping List for a
Departmental Store. The list include details such as the Code No and Price of each
item and perform the operations like Adding, Deleting Items to the list and Printing
the Total value of an Order.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 11
Results:
S.NO DESCRIPTION WEIGHTAGE MARK AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 12
Date:
Friend Function & Friend Class
Exercise 3
Friend Function:
Data hiding is a fundamental concept of object-oriented programming. It restricts the access
of private members from outside of the class. Similarly, protected members can only be
accessed by derived classes and are inaccessible from outside.
For example,
class MyClass {
private:
int member1;
}
int main() {
MyClass obj;
// Error! Cannot access private members from here.
obj.member1 = 5;
}
However, there is a feature in C++ called friend functions that break this rule and allow us to
access member functions from outside the class.
Friend Function in C++
A friend function can access the private and protected data of a class. We declare a friend
function using the friend keyword inside the body of the class.
Syntax :
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
A friend function can be given a special grant to access private and protected members. A
friend function can be:
a) A member of another class
b) A global function
Following are some important points about friend functions and classes:
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 13
1) Friends should be used only for limited purpose. too many functions or external classes are
declared as friends of a class with protected or private data, it lessens the value of
encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A
automatically.
3) Friendship is not inherited
4) The concept of friends is not there in Java.
Sample Program:
1. Sample C++ program to demonstrate the working of friend function
#include <iostream>
using namespace std;
class Distance {
private:
int meter;
// friend function
friend int addFive(Distance);
public:
Distance() : meter(0) {}
};
// friend function definition
int addFive(Distance d)
{
//accessing private members from the friend function
d.meter += 5;
return d.meter;
}
int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}
Output
Distance: 5
Here, addFive() is a friend function that can access both private and public data members.
Though this example gives us an idea about the concept of a friend function, it doesn't show
any meaningful use.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 14
Sample Program:
1. Program to add members of two different classes using friend functions.
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
private:
int numA;
// friend function declaration
friend int add(ClassA, ClassB);
};
class ClassB {
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
private:
int numB;
// friend function declaration
friend int add(ClassA, ClassB);
};
// access members of both classes
int add(ClassA objectA, ClassB objectB) {
return (objectA.numA + objectB.numB);
}
int main() {
ClassA objectA;
ClassB objectB;
cout << "Sum: " << add(objectA, objectB);
return 0;
}
Output :
Sum: 13
In this program, ClassA and ClassB have declared add() as a friend function. Thus, this
function can access private data of both classes. One thing to notice here is the friend
function inside ClassA is using the ClassB. However, we haven't defined ClassB at this point.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 15
// inside classA
friend int add(ClassA, ClassB);
For this to work, we need a forward declaration of ClassB in our program.
// forward declaration
class ClassB;
Friend Class in C++ :
We can also use a friend Class in C++ using the friend keyword.
For example,
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
When a class is declared a friend class, all the member functions of the friend class become
friend functions. Since ClassB is a friend class, we can access all members of ClassA from
inside ClassB. However, we cannot access members of ClassB from inside ClassA. It is
because friend relation in C++ is only granted, not taken.
Sample Program: C++ friend Class
1. C++ program to demonstrate the working of friend class
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
private:
int numA;
// friend class declaration
friend class ClassB;
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 16
};
class ClassB {
private:
int numB;
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
// member function to add numA
// from ClassA and numB from ClassB
int add() {
ClassA objectA;
return objectA.numA + numB;
}
};
int main() {
ClassB objectB;
cout << "Sum: " << objectB.add();
return 0;
}
Output
Sum: 13
Here, ClassB is a friend class of ClassA. So, ClassB has access to the members of classA. In
ClassB, we have created a function add() that returns the sum of numA and numB. Since
ClassB is a friend class, we can create objects of ClassA inside of ClassB.
Lab Exercise:
1. Write a C++ program to calculate and print the length of a box using friend function
and friend class.
Extra Question:
1. Write a C++ program using a member function to get the student details
-Roll no
-Name
-Marks
of five students. Use friend function to display the percentage of marks.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 17
Results:
S.NO DESCRIPTION WEIGHTAGE MARK AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 18
Date:
Function Overloading
Exercise 4
C++ Overloading:
If we create two or more members having the same name but different in number or
type of parameter, it is known as C++ overloading. In C++, we can overload:
• Methods,
• Constructors, and
• Indexed properties
It is because these members have parameters only.
Types of overloading in C++ are:
• Function overloading
• Operator overloading
Function Overloading :
In C++, two functions can have the same name if the number and/or type of arguments
passed is different. These functions having the same name but different arguments are known
as overloaded functions.
For example:
// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Here, all 4 functions are overloaded functions. Notice that the return types of all these 4
functions are not the same. Overloaded functions may or may not have different return types
but they must have different arguments.
For example,
// Error code
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, the same type, and the same number of arguments.
Hence, the compiler will throw an error.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 19
Sample Program:
1. C++ program to implement Function Overloading Using Different Types of
Parameter
// Program to compute absolute value
// Works for both int and float
#include <iostream>
using namespace std;
// function with float type parameter
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
// function with int type parameter
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
int main() {
// call function with int type parameter
cout << "Absolute value of -5 = " << absolute(-5) << endl;
// call function with float type parameter
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}
Output
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
Sample Program:
1. C++ program to implement Function Overloading Using Different Number of
Parameters
#include <iostream>
using namespace std;
// function with 2 parameters
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 20
void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}
// function with double type single parameter
void display(double var) {
cout << "Double number: " << var << endl;
}
// function with int type single parameter
void display(int var) {
cout << "Integer number: " << var << endl;
}
int main() {
int a = 5;
double b = 5.5;
// call function with int type parameter
display(a);
// call function with double type parameter
display(b);
// call function with 2 parameters
display(a, b);
return 0;
}
Output
Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5
Here, the display() function is called three times with different arguments. Depending on the
number and type of arguments passed, the corresponding display() function is called.
Lab Exercise:
1. Write a C++ program to overload a function area() that finds the area of different solids.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 21
Extra Questions:
1. Write a C++ program to find volume of different shapes using function overloading.
2. Write a C++ program to define three overloaded function to swap two integers.
Result:
S.NO DESCRIPTION WEIGHTAGE MARK AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 22
Date:
Operator Overloading
Exercise 5
C++ Overloading:
If we create two or more members having the same name but different in number or
type of parameter, it is known as C++ overloading. In C++, we can overload:
• Methods,
• Constructors, and
• Indexed properties
It is because these members have parameters only.
Types of overloading in C++ are:
• Function overloading
• Operator overloading
Function Overloading
Function overloading is a feature in C++ where two or more functions can have the
same name but different parameters. Function overloading can be considered as an example
of polymorphism feature in C++.
Sample Program:
1. C++ program to implement function overloading for printing values of various data
types.
#include<iostream>
using namespace std;
class PrintData
{
public:
void print(int i)
{
cout<<"Printing int: "<<i<<endl;
}
void print(double f)
{
cout<<"Printing float: "<< f <<endl;
}
void print(char* c)
{
cout<<"Printing character: "<< c <<endl;
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 23
}
};
int main(void)
{
PrintData pd;
pd.print(5);// Call print to print integer
pd.print(500.263);// Call print to print float
pd.print("Hello C++");// Call print to print character
return0;
}
Output:
Here is int 10
Here is float 10.1
Here is char*ten
Operator overloading in C++
The programmer can redefine or overload most of the built-in operators available in C++.
Thus a programmer can use operators with user-defined types as well. Overloaded operators are
functions with special names the keyword operator followed by the symbol for the operator being
defined. Like any other function, an overloaded operator has a return type and a parameter list.
Boxoperator+ (constBox&);
Declares the addition operator that can be used to add two Box objects and returns final Box
object. Most overloaded operators may be defined as ordinary non-member functions or as
class member functions. In case we define above function as non-member function of a class
then we would have to pass two arguments for each operand as follows:
Boxoperator+(constBox, constBox&);
Following is the example to show the concept of operator over loading using a member
function. Here an object is passed as an argument whose properties will be accessed using
this object, the object which will call this operator can be accessed using this operator as
explained below:
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 24
Sample Program:
1. Write a C++ program by creating a class named Box and implement operator
overloading by adding two box objects.
#include<iostream>
Using namespace std;
class 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;
}
Boxoperator+ (constBox& b)// Overload + operator to add two Box objects
{
Box box;
box.length=this->length +b.length;
box.breadth=this->breadth +b.breadth;
box.height=this->height +b.height;
return box;
}
private:
double length; // Length of a box
double breadth;// Breadth of a box
double height; // Height of a box
};
int main ()// Main function for the program
{
Box Box1; // Declare Box1 of type Box
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 25
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 Box1.setLength (6.0); // box 1 specification
Box1.setBreadth (7.0);
Box1.setHeight (5.0);
Box2.setLength (12.0); // box 2 specification
Box2.setBreadth (13.0);
Box2.setHeight (10.0);
volume=Box1.getVolume (); // volume of box 1
cout<<"Volume of Box1: "<< volume <<endl;
volume=Box2.getVolume (); // volume of box 2
cout<<"Volume of Box2: "<< volume <<endl;
Box3=Box1+Box2; // Add two object as follows:
volume=Box3.getVolume (); // volume of box 3
cout<<"Volume of Box3: "<< volume <<endl;
return0;
}
Output:
Volume of Box1:210
Volume of Box2:1560
Volume of Box3:5400
Overloadable/Non-overloadable Operators:
Following is the list of operators which can be overloaded:
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* New new [] delete delete []
Following is the list of operators, which cannot be overloaded:
:: .* . ?:
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 26
Lab Exercise:
1. Write a C++ program converting feet and inch value using unary operator.
Extra Question:
1. Write a C++ program to overload binary operator '+' to add two complex numbers.
Result:
S.NO DESCRIPTION WEIGHTAGE MARK AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 27
Date:
Inheritance
Exercise 6
Inheritance:
One of the most important concepts in object-oriented programming is that of 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.
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
Where access-specifier is one of public, protected, or private, and base-class is the
name of a previously defined class. If the access-specifier is not used, then it is private
by default.
Sample Program:
1. Write a C++ program to implement inheritance by using Shape as base class and
Rectangle as derived class and find the area of Rectangle.
#include<iostream>
using namespace std;
class Shape// Base class
{
public:
voidsetWidth(int w)
{
width= w;
}
voidsetHeight(int h)
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 28
{
height= h;
}
protected:
int width;
int height;
};
class Rectangle : public Shape// derived class
{
public:
intgetArea()
{
return(width * height);
}
};
int main (void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
cout<<"Total area: "<<Rect.getArea ()<<endl;// Print the area of the object.
return0;
}
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.
The different access types according to who can access them in the following way:
Access public Protected private
Same class yes Yes Yes
Derived
Yes Yes No
Classes
Outside
Yes No No
Classes
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 29
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.
Type of Inheritance: When deriving a class from a base class, the base class
may be inherited through public, protected or private inheritance.
• Public Inheritance: When deriving a class from a public base class, public members
of the base class become public members of the derived class and protected members
of the base class become protected members of the derived class. A base class's
private members are never accessible directly from a derived class, but can be
accessed through calls to the public and protected members of the class.
• Protected Inheritance: When deriving from a protected base class, public and
protected members of the base class become protected members of the derived class.
• Private Inheritance: When deriving from a private base class, public and protected
members of the base class become private members of the derived 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 as shown above. Let us try the following example:
Sample Program:
1. Write a C++ program to implement Multiple Inheritance by using Shape and
PaintCost as base class and Rectangle as derived class, then use appropriate function
to find the cost calculation for the total area.
#include<iostream>
Usingnamespace std;
class Shape // Base class Shape
{
public:
void setWidth(int w)
{
width= w;
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 30
}
voidsetHeight(int h)
{
height= h;
}
protected:
int width;
int height;
};
classPaintCost
{
public:
intgetCost(int area)
{
return area *70;
}
};
classRectangle:publicShape,publicPaintCost // Derived class
{
public:
intgetArea()
{
return(width * height);
}
};
int main(void)
{
RectangleRect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area=Rect.getArea();
cout<<"Total area: "<<Rect.getArea()<<endl;// Print the area of the object.
cout<<"Total paint cost: $"<<Rect.getCost(area)<<endl;// Print the total
cost of painting return0;
}
Output:
Total area: 35
Total paint cost: $2450
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 31
Lab Exercise:
1. Write a C++ program to calculate the percentage of a student using multi-level
inheritance. Accept the marks of three subjects in base class. A class will derived
from the above mentioned class which includes a function to find the total marks
obtained and another class derived from this class which calculates and displays the
percentage of student.
Extra Questions:
1. Write a C++ program with 2 base class named animals and birds. Derive from those
base class and print any 3 animals and birds in derived class.
2. Write a C++ program to implement the following and give a brief description about
the identified inheritance :
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 32
Result:
S.NO DESCRIPTION WEIGHTAGE MARK AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 33
Date:
PROGRAMS USING VIRTUAL FUNCTIONS
Exercise 7
Virtual Function: A virtual function is a function in a base class that is declared using the
keyword virtual. Defining in a base class a virtual function, with another version in a derived
class, signals to the compiler that we don't want static linkage for this function. The selection
of the function to be called at any given point in the program to be based on the kind of
object for which it is called. This sort of operation is referred to as dynamic linkage, or late
binding.
Once a member function is declared as a virtual function in a base class, it becomes virtual in
every class derived from that base class. In other words, it is not necessary to use the
keyword virtual in the derived class while declaring redefined versions of the virtual base
class function.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 34
Sample Program:
1. Write a C++ program to implement virtual function fun() in Class A, B and C
#include<iostream>
using namespace std;
class A {
public:
virtual void fun()
{ cout<<"n A::fun() called ";}
};
class B: public A {
public:
void fun()
{ cout<<"n B::fun() called "; }
};
class C: public B {
public:
void fun()
{ cout<<"n C::fun() called "; }
};
int main()
{
C c; // An object of class C
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 35
B *b = &c; // A pointer of type B* pointing to c
b->fun(); // this line prints "C::fun() called"
getchar();
return 0;
}
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all function cannot be provided in a base class because we
don’t know the implementation. Such a class is called abstract class. For example, let Shape
be a base class. We cannot provide implementation of function draw() in Shape, but we know
every derived class must have implementation of draw(). Similarly an Animal class doesn’t
have implementation of move() (assuming that all animals move), but all animals must know
how to move. We cannot create objects of abstract classes.
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t
have implementation, we only declare it. A pure virtual function is declared by assigning 0 in
declaration. See the following example.
Sample Program:
1. Write a C++ program to implement pure virtual function fun() by using Base class
and Derived Class.
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
// This class inherits from Base and implements fun()
class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};
int main(void)
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 36
{
Derived d;
d.fun();
return 0;
}
Output:
fun() called
Lab Exercise:
1. Create a base class shape. Use this class to store two double type values that could be
used to compute area of figures. Derive two specific classes called triangle and
rectangle from the base shape. Add to the base a member function getdata() to
initialize base class data member and another member function display_area() to
compute and display the area of figures. Make display_area() as a virtual function and
redefine it the derived class to suit their requirements.
Extra Questions:
1. Consider an example of a book shop which sells book and video tapes. These two
classes are inherited from the base class called media. The media class has command
data members such as title and publication. The book class has data members for storing
number of pages in book and tape class has the playing time in a tape. Each class will
have member function such as read () and show () in the base class, these members have
to be defined as virtual functions.
2. Write a program which models the class hierarchy for the book and process the
objects of these classes using pointers to the base class.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 37
Results:
S.NO DESCRIPTION WEIGHTAGE
MARK
AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 38
Date:
Programs Using Functions and Class Templates
Exercise 8
Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming. Generic
programming is a technique where generic types are used as parameters in algorithms so that
they can work for a variety of data types.
Templates can be represented in two ways:
• Function templates
• Class templates
Function Templates:
We can define a template for a function. For example, if we have an add() function, we can
create versions of the add function for adding the int, float or double type values.
Class Template:
We can define a template for a class. For example, a class template can be created for the
array class that can accept the array of various types such as int array, float array or double
array.
Function Template
• Generic functions use the concept of a function template. Generic functions define a
set of operations that can be applied to the various types of data.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 39
• The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
• For example, Quick sorting algorithm is implemented using a generic function, it can
be implemented to an array of integers or array of floats.
• A Generic function is created by using the keyword template. The template defines
what function will do.
Syntax of Function Template
template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Where Ttype: It is a placeholder name for a data type used by the function. It is used within
the function definition. It is only a placeholder that the compiler will automatically replace
this placeholder with the actual data type.
class: A class keyword is used to specify a generic type in a template declaration.
Simple Program:
1. Write a simple C++ program for function template
#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;
}
int main()
{
int i =2;
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 40
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Function Templates with Multiple Parameters
We can use more than one generic type in the template function by using the comma to
separate the list.
Syntax
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
In the above syntax, we have seen that the template function can accept any number of
arguments of a different type.
Simple Program:
1. Write a C++ program to implement template function which accepts any number of
arguments of different type
#include <iostream>
using namespace std;
template<class X,class Y> void fun(X a,Y b)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 41
}
int main()
{
fun(15,12.3);
return 0;
}
CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a class uses
the concept of Template, then the class is known as generic class.
Syntax
template<class Ttype>
class class_name
{
}
Ttype is a placeholder name which will be determined when the class is instantiated. We can
define more than one generic data type using a comma-separated list. The Ttype can be used
inside the class body.
Now, we create an instance of a class
class_name<type> ob;
where class_name: It is the name of the class.
type: It is the type of the data that the class is operating on.
ob: It is the name of the object.
Sample Program:
1. Write a C++ program to implement class template for addition of two numbers.
#include <iostream>
using namespace std;
template<class T>
class A
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 42
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
}
};
int main()
{
A<int> d;
d.add();
return 0;
}
Output:
Addition of num1 and num2: 11
In the above example, we create a template for class A. Inside the main() method, we create
the instance of class A named as, 'd'.
CLASS TEMPLATE WITH MULTIPLE PARAMETERS
We can use more than one generic data type in a class template, and each generic data type is
separated by the comma.
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
Sample Program:
1. Write a C++ program to implement class template contains two generic data types.
#include <iostream>
using namespace std;
template<class T1, class T2>
class A
{
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 43
T1 a;
T2 b;
public:
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
std::cout << "Values of a and b are: " << a<<" ,"<<b<<std::endl;
}
};
int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}
Output:
Values of a and b are : 5,6.5
Lab Exercise:
1. Write a C++ program to swap two numbers using function templates.
Extra Question:
1. Write a C++ program to find the largest between numbers using the Function Template.
2. Write a C++ program to perform Simple calculator operations using Class template.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 44
Result:
S.NO DESCRIPTION WEIGHTAGE
MARK
AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 45
Date:
Files and Streams
Exercise 9
Files
Files are used to store data in a storage device permanently. File handling provides a
mechanism to store the output of a program in a file and to perform various operations on it.
A stream is an abstraction that represents a device on which operations of input and output
are performed. A stream can be represented as a source or destination of characters of
indefinite length depending on its usage.
In C++ we have a set of file handling methods. These include ifstream, ofstream, and fstream.
These classes are derived from fstrembase and from the corresponding iostream class. These
classes, designed to manage the disk files, are declared in fstream and therefore we must
include fstream and therefore we must include this file in any program that uses files.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
• ofstream: This Stream class signifies the output file stream and is applied to create
files for writing information to files
• ifstream: This Stream class signifies the input file stream and is applied for reading
information from files
• fstream: This Stream class can be used for both read and write from/to files.
All the above three classes are derived from fstream base and from the corresponding
iostream class and they are designed specifically to manage disk files.
C++ provides us with the following operations in File Handling:
• Creating a file: open()
• Reading data: read()
• Writing new data: write()
• Closing a file: close()
Opening a File
First operation performed on an object of one of these classes is to associate it to a real file.
This procedure is known to open a file. We can open a file using any one of the following
methods.
1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open() function.
To open a file use
open() function
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 46
Syntax
void open(const char* file_name,ios::openmode mode);
Here, the first argument of the open function defines the name and format of the file with the
address of the file.
The second argument represents the mode in which the file has to be opened.
Example
fstream new_file;
new_file.open(“newfile.txt”, ios::out);
Sample Program:
1. Write C++ FileStream program to create or open a file using the open()
function
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}
2. Write a C++ FileStream program to write to a file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream filestream("testout.txt");
if (filestream.is_open())
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 47
{
filestream << "Welcome to javaTpoint.n";
filestream << "C++ Tutorial.n";
filestream.close();
}
else
cout <<"File opening is fail.";
return 0;
}
3. Write a C++ FileStream program to read from a file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else
{
cout << "File opening is fail."<<endl;
}
return 0;
}
4. Write a C++ FileStream program to close a File
It is simply done with the help of close() function.
Syntax: File Pointer.close()
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 48
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
}
Lab Exercise:
1. Write a program that opens a file, reads its contents, and changes any vowels it
finds to a ‘#’ symbol and finally close a file
Extra Question:
1. Write a program that merges the numbers in two files and writes all the numbers
into a third file. Your program takes input from two different files and writes its
output to a third file. Each input file contains a list of numbers of type int in sorted
order from the smallest to the largest. After the program is run, the output file will
contain all the numbers in the two input files in one longer list in sorted order
from smallest to largest. Your program should define a function that is called with
the two input-file streams and the output-file stream as three arguments.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 49
Result:
S.NO DESCRIPTION WEIGHTAGE
MARK
AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 50
Date:
Exception Handling
Exercise 10
Exception Handling
Exception Handling in C++ is a process to handle runtime errors. We perform exception
handling so the normal flow of the application can be maintained even after runtime errors.
In C++, exception is an event or object which is thrown at runtime. All exceptions are
derived from std::exception class. It is a runtime error which can be handled. If we don't
handle the exception, it prints exception message and terminates the program.
In C++, we use 3 keywords to perform exception handling:
• try
• catch, and
• throw
Why Exception Handling?
Following are main advantages of exception handling over traditional error handling.
1) Separation of Error Handling code from Normal Code: In traditional error handling
codes, there are always if else conditions to handle errors. These conditions and the code to
handle errors get mixed up with the normal flow. This makes the code less readable and
maintainable. With try catch blocks, the code for error handling becomes separate from the
normal flow.
2) Functions/Methods can handle any exceptions they choose: A function can throw many
exceptions, but may choose to handle some of them. The other exceptions which are thrown,
but not caught can be handled by caller. If the caller chooses not to catch them, then the
exceptions are handled by caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw keyword. The
caller of this function must handle the exception in some way (either by specifying it again or
catching it)
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 51
3) Grouping of Error Types: In C++, both basic types and objects can be thrown as
exception. We can create a hierarchy of exception objects, group exceptions in namespaces or
classes, categorize them according to types.
Rethrowing Exceptions:
• Rethrowing an expression from within an exception handler can be done by calling
throw, by itself, with no exception.
• This causes current exception to be passed on to an outer try/catch sequence. An
exception can only be rethrown from within a catch block.
• When an exception is rethrown, it is propagated outward to the next catch block
Sample Program:
1. Write a C++ program to rethrow an exception.
#include <iostream>
using namespace std;
void MyHandler()
{
try
{
throw “hello”;
}
catch (const char*)
{
cout <<”Caught exception inside MyHandlern”;
throw; //rethrow char* out of function
}
}
int main()
{
cout<< “Main start”;
try
{
MyHandler();
}
catch(const char*)
{
cout <<”Caught exception inside Mainn”;
}
cout << “Main end”;
return 0;}
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 52
Exception Handling in C++
Following is a simple example to show exception handling in C++. The output of program
explains flow of execution of try/catch blocks.
Sample Program:
1. Write a simple C++ program to show exception handling.
#include <iostream>
using namespace std;
int main()
{
int x = -1;
cout << "Before try n";
try {
cout << "Inside try n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) n";
}
}
catch (int x ) {
cout << "Exception Caught n";
}
cout << "After catch (Will be executed) n";
return 0;
}
Output
Before try
Inside try
Exception Caught
After catch (Will be executed)
2. Write a C++ program to throw exception for divide by zero error.
#include <iostream>
using namespace std;
float division(int x, int y) {
if( y == 0 ) {
throw "Attempted to divide by zero!";
}
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 53
return (x/y);
}
int main ()
{
int i = 25;
int j = 0;
float k = 0;
try
{
k = division(i, j);
cout << k << endl;
}catch (const char* e)
{
cerr << e << endl;
}
return 0;
}
User Defined Exceptions
The new exception can be defined by overriding and inheriting exception class functionality.
The C++ std::exception class allows us to define objects that can be thrown as exceptions.
This class has been defined in the <exception> header. The class provides us with a virtual
member function named what.
This function returns a null-terminated character sequence of type char *. We can overwrite it
in derived classes to have an exception description.
Sample Program:
1. Write a C++ program to create and throw a user defined exception if the condition
"divide by zero" occurs.
#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception{
public:
const char * what() const throw()
{
return "Attempted to divide by zero!n";
}
};
int main()
{
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 54
try
{
int x, y;
cout << "Enter the two numbers : n";
cin >> x >> y;
if (y == 0)
{
MyException z;
throw z;
}
else
{
cout << "x / y = " << x/y << endl;
}
}
catch(exception& e)
{
cout << e.what();
}
}
Lab Exercise:
1. Write a C++ program that converts 24-hour time to 12-hour time. The following is a
sample output:
Enter time in 24-hour notation:
13:07
That is the same as
1:07 PM
Again?(y/n)
y
Enter time in 24-hour notation:
10:15
That is the same as
10:15 AM
Again?(y/n)
y
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 55
You will define an exception class called TimeFormatMistake. If the user enters an illegal
time, like 10:65 or even gibberish like 8&*68, then your program will throw and catch a
TimeFormatMistake.
Extra Question:
1. Write a program to detect and throw an exception if the condition "divide by zero"
occurs by using appropriate try, catch and throw blocks.
Department of Computer Science and Engineering
20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 56
Result:
S.NO DESCRIPTION WEIGHTAGE
MARK
AWARDED
1
Algorithm and Program
Implementation 10
2
Experimental Results And
Analysis
10
3 Viva-voce 10
Total 30
Signature of the Faculty

More Related Content

Similar to OOPS_Lab_Manual - programs using C++ programming language

22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf
PradipShinde53
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
ahmed hmed
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
Asfand Hassan
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
Revathiparamanathan
 
12. MODULE 1.pptx
12. MODULE 1.pptx12. MODULE 1.pptx
12. MODULE 1.pptx
NIKHILAG9
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
akreyi
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
sidra tauseef
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
rumanatasnim415
 
Lecture 3.2.4 C pointer to Structure.pptx
Lecture 3.2.4 C pointer to Structure.pptxLecture 3.2.4 C pointer to Structure.pptx
Lecture 3.2.4 C pointer to Structure.pptx
ravi2692kumar
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
rehan16091997
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
study material
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#
ANURAG SINGH
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
Aadil Ansari
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
Rai University
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
Rai University
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEW
shyamuopten
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
C++ basic
C++ basicC++ basic
C++ basic
TITTanmoy
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
Amresh Raj
 

Similar to OOPS_Lab_Manual - programs using C++ programming language (20)

22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
 
12. MODULE 1.pptx
12. MODULE 1.pptx12. MODULE 1.pptx
12. MODULE 1.pptx
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
Lecture 3.2.4 C pointer to Structure.pptx
Lecture 3.2.4 C pointer to Structure.pptxLecture 3.2.4 C pointer to Structure.pptx
Lecture 3.2.4 C pointer to Structure.pptx
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEW
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
 
C++ basic
C++ basicC++ basic
C++ basic
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 

Recently uploaded

System Analysis and Design in a changing world 5th edition
System Analysis and Design in a changing world 5th editionSystem Analysis and Design in a changing world 5th edition
System Analysis and Design in a changing world 5th edition
mnassar75g
 
UNIT 1 - INTRODUCTION ON DISASTER MANAGEMENT.ppt
UNIT 1 - INTRODUCTION ON DISASTER MANAGEMENT.pptUNIT 1 - INTRODUCTION ON DISASTER MANAGEMENT.ppt
UNIT 1 - INTRODUCTION ON DISASTER MANAGEMENT.ppt
shanmugamram247
 
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
amzhoxvzidbke
 
Indian Railway Signalling concepts and basics.pdf
Indian Railway Signalling concepts and basics.pdfIndian Railway Signalling concepts and basics.pdf
Indian Railway Signalling concepts and basics.pdf
princeshah76
 
Ebara corporation introduction. looking ahead, going beyond expectation
Ebara corporation introduction. looking ahead, going beyond expectationEbara corporation introduction. looking ahead, going beyond expectation
Ebara corporation introduction. looking ahead, going beyond expectation
nanjay2
 
AI INTRODUCTION Artificial intelligence.ppt
AI INTRODUCTION Artificial intelligence.pptAI INTRODUCTION Artificial intelligence.ppt
AI INTRODUCTION Artificial intelligence.ppt
GeethaAL
 
Chapter 1 Introduction to Software Engineering and Process Models.pdf
Chapter 1 Introduction to Software Engineering and Process Models.pdfChapter 1 Introduction to Software Engineering and Process Models.pdf
Chapter 1 Introduction to Software Engineering and Process Models.pdf
MeghaGupta952452
 
Machine Learning_SVM_KNN_K-MEANSModule 2.pdf
Machine Learning_SVM_KNN_K-MEANSModule 2.pdfMachine Learning_SVM_KNN_K-MEANSModule 2.pdf
Machine Learning_SVM_KNN_K-MEANSModule 2.pdf
Dr. Shivashankar
 
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdfLOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
jellyjm
 
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdfRed Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
mdfkobir
 
Generative AI and Large Language Models (LLMs)
Generative AI and Large Language Models (LLMs)Generative AI and Large Language Models (LLMs)
Generative AI and Large Language Models (LLMs)
rkpv2002
 
carpentry-11-module-1.docx 1 identifying tools
carpentry-11-module-1.docx 1 identifying toolscarpentry-11-module-1.docx 1 identifying tools
carpentry-11-module-1.docx 1 identifying tools
ChristopherAltizen2
 
AI chapter1 introduction to artificial intelligence
AI chapter1 introduction to artificial intelligenceAI chapter1 introduction to artificial intelligence
AI chapter1 introduction to artificial intelligence
GeethaAL
 
Kerong Gas Gas Recovery System Catalogue.pdf
Kerong Gas Gas Recovery System Catalogue.pdfKerong Gas Gas Recovery System Catalogue.pdf
Kerong Gas Gas Recovery System Catalogue.pdf
Nicky Xiong熊妮
 
李易峰祝绪丹做爱视频流出【网芷:ht28.co】可爱学生妹>>>[网趾:ht28.co】]<<<
李易峰祝绪丹做爱视频流出【网芷:ht28.co】可爱学生妹>>>[网趾:ht28.co】]<<<李易峰祝绪丹做爱视频流出【网芷:ht28.co】可爱学生妹>>>[网趾:ht28.co】]<<<
李易峰祝绪丹做爱视频流出【网芷:ht28.co】可爱学生妹>>>[网趾:ht28.co】]<<<
amzhoxvzidbke
 
Human_assault project using jetson nano new
Human_assault project using jetson nano newHuman_assault project using jetson nano new
Human_assault project using jetson nano new
frostflash010
 
The Control of Relative Humidity & Moisture Content in The Air
The Control of Relative Humidity & Moisture Content in The AirThe Control of Relative Humidity & Moisture Content in The Air
The Control of Relative Humidity & Moisture Content in The Air
Ashraf Ismail
 
Developing a Genetic Algorithm Based Daily Calorie Recommendation System for ...
Developing a Genetic Algorithm Based Daily Calorie Recommendation System for ...Developing a Genetic Algorithm Based Daily Calorie Recommendation System for ...
Developing a Genetic Algorithm Based Daily Calorie Recommendation System for ...
AIRCC Publishing Corporation
 
Safety Operating Procedure for Testing Lifting Tackles
Safety Operating Procedure for Testing Lifting TacklesSafety Operating Procedure for Testing Lifting Tackles
Safety Operating Procedure for Testing Lifting Tackles
ssuserfcf701
 
JORC_Review_presentation. 2024 código jorcpdf
JORC_Review_presentation. 2024 código jorcpdfJORC_Review_presentation. 2024 código jorcpdf
JORC_Review_presentation. 2024 código jorcpdf
WilliamsNuezEspetia
 

Recently uploaded (20)

System Analysis and Design in a changing world 5th edition
System Analysis and Design in a changing world 5th editionSystem Analysis and Design in a changing world 5th edition
System Analysis and Design in a changing world 5th edition
 
UNIT 1 - INTRODUCTION ON DISASTER MANAGEMENT.ppt
UNIT 1 - INTRODUCTION ON DISASTER MANAGEMENT.pptUNIT 1 - INTRODUCTION ON DISASTER MANAGEMENT.ppt
UNIT 1 - INTRODUCTION ON DISASTER MANAGEMENT.ppt
 
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
 
Indian Railway Signalling concepts and basics.pdf
Indian Railway Signalling concepts and basics.pdfIndian Railway Signalling concepts and basics.pdf
Indian Railway Signalling concepts and basics.pdf
 
Ebara corporation introduction. looking ahead, going beyond expectation
Ebara corporation introduction. looking ahead, going beyond expectationEbara corporation introduction. looking ahead, going beyond expectation
Ebara corporation introduction. looking ahead, going beyond expectation
 
AI INTRODUCTION Artificial intelligence.ppt
AI INTRODUCTION Artificial intelligence.pptAI INTRODUCTION Artificial intelligence.ppt
AI INTRODUCTION Artificial intelligence.ppt
 
Chapter 1 Introduction to Software Engineering and Process Models.pdf
Chapter 1 Introduction to Software Engineering and Process Models.pdfChapter 1 Introduction to Software Engineering and Process Models.pdf
Chapter 1 Introduction to Software Engineering and Process Models.pdf
 
Machine Learning_SVM_KNN_K-MEANSModule 2.pdf
Machine Learning_SVM_KNN_K-MEANSModule 2.pdfMachine Learning_SVM_KNN_K-MEANSModule 2.pdf
Machine Learning_SVM_KNN_K-MEANSModule 2.pdf
 
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdfLOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
 
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdfRed Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
 
Generative AI and Large Language Models (LLMs)
Generative AI and Large Language Models (LLMs)Generative AI and Large Language Models (LLMs)
Generative AI and Large Language Models (LLMs)
 
carpentry-11-module-1.docx 1 identifying tools
carpentry-11-module-1.docx 1 identifying toolscarpentry-11-module-1.docx 1 identifying tools
carpentry-11-module-1.docx 1 identifying tools
 
AI chapter1 introduction to artificial intelligence
AI chapter1 introduction to artificial intelligenceAI chapter1 introduction to artificial intelligence
AI chapter1 introduction to artificial intelligence
 
Kerong Gas Gas Recovery System Catalogue.pdf
Kerong Gas Gas Recovery System Catalogue.pdfKerong Gas Gas Recovery System Catalogue.pdf
Kerong Gas Gas Recovery System Catalogue.pdf
 
李易峰祝绪丹做爱视频流出【网芷:ht28.co】可爱学生妹>>>[网趾:ht28.co】]<<<
李易峰祝绪丹做爱视频流出【网芷:ht28.co】可爱学生妹>>>[网趾:ht28.co】]<<<李易峰祝绪丹做爱视频流出【网芷:ht28.co】可爱学生妹>>>[网趾:ht28.co】]<<<
李易峰祝绪丹做爱视频流出【网芷:ht28.co】可爱学生妹>>>[网趾:ht28.co】]<<<
 
Human_assault project using jetson nano new
Human_assault project using jetson nano newHuman_assault project using jetson nano new
Human_assault project using jetson nano new
 
The Control of Relative Humidity & Moisture Content in The Air
The Control of Relative Humidity & Moisture Content in The AirThe Control of Relative Humidity & Moisture Content in The Air
The Control of Relative Humidity & Moisture Content in The Air
 
Developing a Genetic Algorithm Based Daily Calorie Recommendation System for ...
Developing a Genetic Algorithm Based Daily Calorie Recommendation System for ...Developing a Genetic Algorithm Based Daily Calorie Recommendation System for ...
Developing a Genetic Algorithm Based Daily Calorie Recommendation System for ...
 
Safety Operating Procedure for Testing Lifting Tackles
Safety Operating Procedure for Testing Lifting TacklesSafety Operating Procedure for Testing Lifting Tackles
Safety Operating Procedure for Testing Lifting Tackles
 
JORC_Review_presentation. 2024 código jorcpdf
JORC_Review_presentation. 2024 código jorcpdfJORC_Review_presentation. 2024 código jorcpdf
JORC_Review_presentation. 2024 código jorcpdf
 

OOPS_Lab_Manual - programs using C++ programming language

  • 1. SRI RAMAKRISHNA INSTITUTE OF TECHNOLOGY AN AUTONOMOUS INSTITUTION COIMBATORE-641010 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING LAB MANUAL 20CSG02 – PROGRAMMING IN C++ LABORATORY FIRST YEAR – SECOND SEMESTER (Common to all Branches) COMPILED BY PREETHA V M.E., AP/CSE VIDYA PRIYA DARCINI S M.Tech., AP/CSE
  • 2. COURSE OBJECTIVE: This course provides a practical experience on the concepts of Object Oriented Programming using C++ programming language. LIST OF EXPERIMENTS: 1. Programs using Objects and Classes 2. Programs using Constructors and Destructors 3. Programs using friend function & friend class. 4. Programs using Function Overloading 5. Programs to overload unary & binary operators as member function & non-member function 6. Programs using types of inheritance 7. Programs using virtual functions 8. Programs using Function and class templates 9. Programs using Files and Streams 10. Programs using Exception handling COURSE OUTCOMES: CO1: Ability to apply the concept related to Classes and Objects in simple programs CO2: Ability to apply the concepts of polymorphism to achieve enhanced functionalities of functions and operator. CO3: Ability to deploy inheritance in simple C++ programs CO4: Ability to design simple applications that support File Processing CO5: Ability to develop programs that are capable of handling Exceptions REFERENCES: 1. Herbert Schildt, “C++ The Complete Reference”, 5th Edition, Tata McGraw Hill, New Delhi, 2. Bjarne Stroustrup, “The C++ Programming Language”, 4th Edition, Addison-Wesley, 2013. 3. Deitel and Deitel, “C++ How to Program”, 10th Edition, Prentice Hall India Learning Private Limited, 2018. 4. Robert Lafore, “Object Oriented Programming in C++”, 4th edition, Pearson India, 2002. 5. Stanley B. Lippman and Josee Lajoie, “C++ Primer”, 5th Edition, Pearson Education, New Delhi, 2013. 6. E.Balagurusamy, “Object Oriented Programming with C++”, 6th Edition, Tata McGraw Hill, 2013.
  • 3. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 1 LIST OF EXPERIMENTS Sl. No. Description Marks Awarded 1 Objects and Classes 2 Constructors and Destructors 3 Friend Function & Friend Class. 4 Function Overloading 5 Operator Overloading 6 Inheritance 7 Virtual functions 8 Function and Class Templates 9 Files and Streams 10 Exception handling Total Average Signature of the Course Instructor
  • 4. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 2 Date: OBJECTS, CLASSES Exercise 1 Class: It is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object. For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties. A Class is a user defined data-type which have data members and member functions. Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class. In the above example of class Car, the data member will be speed limit, mileage etc. and member functions can be apply brakes, increase speed etc. Object: An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside the curly brackets and terminated by a semicolon at the end. Fig :1.1 Defining Class and Declaring Objects Declaring Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.
  • 5. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 3 Syntax: Class_Name Object_Name; Sample Program: 1. Define a class named Student which includes id, name as Data members and insert(), display() as the member functions to insert the id and name and display the same respectively. #include <iostream> using namespace std; class Student { public: int id;//data member (also instance variable) string name;//data member(also instance variable) void insert(int i, string n) { id = i; name = n; } void display() { cout<<id<<" "<<name<<endl; } }; int main(void) { Student s1; //creating an object of Student Student s2; //creating an object of Student s1.insert(201, "Sonoo"); s2.insert(202, "Nakul"); s1.display(); s2.display(); return 0; } Output: 201 Sonoo 202 Nakul
  • 6. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 4 Lab Question: 1. Define a class to represent a bank account which includes the following members as Data members: a) Name of the depositor b) Account Number c) Amount and the member functions are a)Withdrawal() c)Deposit() b) Display_Balance(). Extra Question: 1. A class defines a blueprint for an object. We use the same syntax to declare objects of a class as we use to declare variables of other basic types. For example: Box box1; // Declares variable box1 of type Box Box box2; // Declare variable box2 of type Box Kristen is a contender for valedictorian of her high school. She wants to know how many students (if any) have scored higher than her in the exams given during this semester. Create a class named Student with the following specifications: • An instance variable named to hold a student's 5 exam scores. • A void input() function that reads 5 integers and saves them to scores. • An int calculateTotalScore() function that returns the sum of the student's scores.
  • 7. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 5 Results: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 8. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 6 Date: CONSTRUCTORS AND DESTRUCTOR Exercise 2 Constructors: A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object (instance of class) create. It is special member function of the class. A constructor is different from normal member functions in following ways: • Constructor has same name as the class itself. • Constructors don’t have return type. • A constructor is automatically called when an object is created. • If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body). Types of Constructors: • Default Constructor • Parameterized Constructor • Copy Constructor Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters. Sample Program: 1. Program to use default constructor for printing two variable values. #include <iostream> using namespace std; class construct { public: int a, b; construct ()// Default Constructor {
  • 9. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 7 a = 10; b = 20; } }; int main () { construct c; // Default constructor called automatically when the object is created cout << "a: "<< c.a << endl << "b: "<< c.b; return 1; } Output: 10 20 Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object. Sample Program: 1. Program to print two variable values by using parameterized Constructor. #include<iostream> using namespace std; class Point { private: int x, y; public: Point(int x1, int y1)// Parameterized Constructor { x = x1; y = y1; } int getX() { return x; } int getY()
  • 10. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 8 { return y; } }; int main() { Point p1(10, 15);// Constructor called cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); // Access values assigned by constructor return 0; } Output: p1.x=10, p1.y=15 Copy Constructor: A copy constructor is a member function which initializes an object using another object of the same class. A copy constructor has the following general function prototype: Class Name (const ClassName &old_obj); Sample Program: 1. Program to print two variable values by using Copy Constructor. #include<iostream> using namespace std; class Point { private: int x, y; public: Point(int x1, int y1) { x = x1; y = y1; } Point(const Point &p2) // Copy constructor { x = p2.x; y = p2.y; }
  • 11. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 9 int getX() int getY() { return x; } { return y; }}; int main() { Point p1(10, 15); // Normal constructor is called here Point p2 = p1; // Copy constructor is called here cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();// Let us access values assigned by constructors cout << "np2.x = " << p2.getX() << ", p2.y = " << p2.getY(); return 0; } Output: p1.x=10, p1.y=15 p2.x=10, p2.y=15 Destructor: Destructor is a member function which destructs or deletes an object. Destructor is called when: A destructor function is called automatically when the object goes out of scope: (1) the function ends (2) the program ends (3) a block containing local variables ends (4) a delete operator is called. Destructors have same name as the class preceded by a tilde (~), destructors don’t take any argument and don’t return anything. Sample Program: 1. Program to use Destructor for deleting an object created using Class String. class String { private: char *s; int size; public:
  • 12. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 10 String(char *); // constructor ~String(); // destructor }; String::String(char *c) { size = strlen(c); s = new char[size+1]; strcpy(s,c); } String::~String() { delete []s; } Lab Exercise: 1. Write a C++ program to calculate the area of triangle, rectangle and circle by using the concepts of default, parameterized and copy constructor. Finally use destructor to delete the objects created. Extra Questions: 1. Write a C++ program to create a class FD a/c which contains member (fdno, name, amt, interest rate, maturity amt & No. of months). Write parameterized constructor where interest rate should be default argument. Calculate maturity amt using interest rate & display all the details. 2. Write a C++ program using copy constructor to process Shopping List for a Departmental Store. The list include details such as the Code No and Price of each item and perform the operations like Adding, Deleting Items to the list and Printing the Total value of an Order.
  • 13. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 11 Results: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 14. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 12 Date: Friend Function & Friend Class Exercise 3 Friend Function: Data hiding is a fundamental concept of object-oriented programming. It restricts the access of private members from outside of the class. Similarly, protected members can only be accessed by derived classes and are inaccessible from outside. For example, class MyClass { private: int member1; } int main() { MyClass obj; // Error! Cannot access private members from here. obj.member1 = 5; } However, there is a feature in C++ called friend functions that break this rule and allow us to access member functions from outside the class. Friend Function in C++ A friend function can access the private and protected data of a class. We declare a friend function using the friend keyword inside the body of the class. Syntax : class className { ... .. ... friend returnType functionName(arguments); ... .. ... } A friend function can be given a special grant to access private and protected members. A friend function can be: a) A member of another class b) A global function Following are some important points about friend functions and classes:
  • 15. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 13 1) Friends should be used only for limited purpose. too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming. 2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically. 3) Friendship is not inherited 4) The concept of friends is not there in Java. Sample Program: 1. Sample C++ program to demonstrate the working of friend function #include <iostream> using namespace std; class Distance { private: int meter; // friend function friend int addFive(Distance); public: Distance() : meter(0) {} }; // friend function definition int addFive(Distance d) { //accessing private members from the friend function d.meter += 5; return d.meter; } int main() { Distance D; cout << "Distance: " << addFive(D); return 0; } Output Distance: 5 Here, addFive() is a friend function that can access both private and public data members. Though this example gives us an idea about the concept of a friend function, it doesn't show any meaningful use.
  • 16. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 14 Sample Program: 1. Program to add members of two different classes using friend functions. #include <iostream> using namespace std; // forward declaration class ClassB; class ClassA { public: // constructor to initialize numA to 12 ClassA() : numA(12) {} private: int numA; // friend function declaration friend int add(ClassA, ClassB); }; class ClassB { public: // constructor to initialize numB to 1 ClassB() : numB(1) {} private: int numB; // friend function declaration friend int add(ClassA, ClassB); }; // access members of both classes int add(ClassA objectA, ClassB objectB) { return (objectA.numA + objectB.numB); } int main() { ClassA objectA; ClassB objectB; cout << "Sum: " << add(objectA, objectB); return 0; } Output : Sum: 13 In this program, ClassA and ClassB have declared add() as a friend function. Thus, this function can access private data of both classes. One thing to notice here is the friend function inside ClassA is using the ClassB. However, we haven't defined ClassB at this point.
  • 17. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 15 // inside classA friend int add(ClassA, ClassB); For this to work, we need a forward declaration of ClassB in our program. // forward declaration class ClassB; Friend Class in C++ : We can also use a friend Class in C++ using the friend keyword. For example, class ClassB; class ClassA { // ClassB is a friend class of ClassA friend class ClassB; ... .. ... } class ClassB { ... .. ... } When a class is declared a friend class, all the member functions of the friend class become friend functions. Since ClassB is a friend class, we can access all members of ClassA from inside ClassB. However, we cannot access members of ClassB from inside ClassA. It is because friend relation in C++ is only granted, not taken. Sample Program: C++ friend Class 1. C++ program to demonstrate the working of friend class #include <iostream> using namespace std; // forward declaration class ClassB; class ClassA { private: int numA; // friend class declaration friend class ClassB; public: // constructor to initialize numA to 12 ClassA() : numA(12) {}
  • 18. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 16 }; class ClassB { private: int numB; public: // constructor to initialize numB to 1 ClassB() : numB(1) {} // member function to add numA // from ClassA and numB from ClassB int add() { ClassA objectA; return objectA.numA + numB; } }; int main() { ClassB objectB; cout << "Sum: " << objectB.add(); return 0; } Output Sum: 13 Here, ClassB is a friend class of ClassA. So, ClassB has access to the members of classA. In ClassB, we have created a function add() that returns the sum of numA and numB. Since ClassB is a friend class, we can create objects of ClassA inside of ClassB. Lab Exercise: 1. Write a C++ program to calculate and print the length of a box using friend function and friend class. Extra Question: 1. Write a C++ program using a member function to get the student details -Roll no -Name -Marks of five students. Use friend function to display the percentage of marks.
  • 19. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 17 Results: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 20. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 18 Date: Function Overloading Exercise 4 C++ Overloading: If we create two or more members having the same name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload: • Methods, • Constructors, and • Indexed properties It is because these members have parameters only. Types of overloading in C++ are: • Function overloading • Operator overloading Function Overloading : In C++, two functions can have the same name if the number and/or type of arguments passed is different. These functions having the same name but different arguments are known as overloaded functions. For example: // same name different arguments int test() { } int test(int a) { } float test(double a) { } int test(int a, double b) { } Here, all 4 functions are overloaded functions. Notice that the return types of all these 4 functions are not the same. Overloaded functions may or may not have different return types but they must have different arguments. For example, // Error code int test(int a) { } double test(int b){ } Here, both functions have the same name, the same type, and the same number of arguments. Hence, the compiler will throw an error.
  • 21. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 19 Sample Program: 1. C++ program to implement Function Overloading Using Different Types of Parameter // Program to compute absolute value // Works for both int and float #include <iostream> using namespace std; // function with float type parameter float absolute(float var){ if (var < 0.0) var = -var; return var; } // function with int type parameter int absolute(int var) { if (var < 0) var = -var; return var; } int main() { // call function with int type parameter cout << "Absolute value of -5 = " << absolute(-5) << endl; // call function with float type parameter cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl; return 0; } Output Absolute value of -5 = 5 Absolute value of 5.5 = 5.5 Sample Program: 1. C++ program to implement Function Overloading Using Different Number of Parameters #include <iostream> using namespace std; // function with 2 parameters
  • 22. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 20 void display(int var1, double var2) { cout << "Integer number: " << var1; cout << " and double number: " << var2 << endl; } // function with double type single parameter void display(double var) { cout << "Double number: " << var << endl; } // function with int type single parameter void display(int var) { cout << "Integer number: " << var << endl; } int main() { int a = 5; double b = 5.5; // call function with int type parameter display(a); // call function with double type parameter display(b); // call function with 2 parameters display(a, b); return 0; } Output Integer number: 5 Float number: 5.5 Integer number: 5 and double number: 5.5 Here, the display() function is called three times with different arguments. Depending on the number and type of arguments passed, the corresponding display() function is called. Lab Exercise: 1. Write a C++ program to overload a function area() that finds the area of different solids.
  • 23. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 21 Extra Questions: 1. Write a C++ program to find volume of different shapes using function overloading. 2. Write a C++ program to define three overloaded function to swap two integers. Result: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 24. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 22 Date: Operator Overloading Exercise 5 C++ Overloading: If we create two or more members having the same name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload: • Methods, • Constructors, and • Indexed properties It is because these members have parameters only. Types of overloading in C++ are: • Function overloading • Operator overloading Function Overloading Function overloading is a feature in C++ where two or more functions can have the same name but different parameters. Function overloading can be considered as an example of polymorphism feature in C++. Sample Program: 1. C++ program to implement function overloading for printing values of various data types. #include<iostream> using namespace std; class PrintData { public: void print(int i) { cout<<"Printing int: "<<i<<endl; } void print(double f) { cout<<"Printing float: "<< f <<endl; } void print(char* c) { cout<<"Printing character: "<< c <<endl;
  • 25. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 23 } }; int main(void) { PrintData pd; pd.print(5);// Call print to print integer pd.print(500.263);// Call print to print float pd.print("Hello C++");// Call print to print character return0; } Output: Here is int 10 Here is float 10.1 Here is char*ten Operator overloading in C++ The programmer can redefine or overload most of the built-in operators available in C++. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list. Boxoperator+ (constBox&); Declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows: Boxoperator+(constBox, constBox&); Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below:
  • 26. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 24 Sample Program: 1. Write a C++ program by creating a class named Box and implement operator overloading by adding two box objects. #include<iostream> Using namespace std; class 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; } Boxoperator+ (constBox& b)// Overload + operator to add two Box objects { Box box; box.length=this->length +b.length; box.breadth=this->breadth +b.breadth; box.height=this->height +b.height; return box; } private: double length; // Length of a box double breadth;// Breadth of a box double height; // Height of a box }; int main ()// Main function for the program { Box Box1; // Declare Box1 of type Box
  • 27. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 25 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 Box1.setLength (6.0); // box 1 specification Box1.setBreadth (7.0); Box1.setHeight (5.0); Box2.setLength (12.0); // box 2 specification Box2.setBreadth (13.0); Box2.setHeight (10.0); volume=Box1.getVolume (); // volume of box 1 cout<<"Volume of Box1: "<< volume <<endl; volume=Box2.getVolume (); // volume of box 2 cout<<"Volume of Box2: "<< volume <<endl; Box3=Box1+Box2; // Add two object as follows: volume=Box3.getVolume (); // volume of box 3 cout<<"Volume of Box3: "<< volume <<endl; return0; } Output: Volume of Box1:210 Volume of Box2:1560 Volume of Box3:5400 Overloadable/Non-overloadable Operators: Following is the list of operators which can be overloaded: + - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= /= %= ^= &= |= *= <<= >>= [] () -> ->* New new [] delete delete [] Following is the list of operators, which cannot be overloaded: :: .* . ?:
  • 28. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 26 Lab Exercise: 1. Write a C++ program converting feet and inch value using unary operator. Extra Question: 1. Write a C++ program to overload binary operator '+' to add two complex numbers. Result: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 29. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 27 Date: Inheritance Exercise 6 Inheritance: One of the most important concepts in object-oriented programming is that of 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. 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 Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default. Sample Program: 1. Write a C++ program to implement inheritance by using Shape as base class and Rectangle as derived class and find the area of Rectangle. #include<iostream> using namespace std; class Shape// Base class { public: voidsetWidth(int w) { width= w; } voidsetHeight(int h)
  • 30. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 28 { height= h; } protected: int width; int height; }; class Rectangle : public Shape// derived class { public: intgetArea() { return(width * height); } }; int main (void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); cout<<"Total area: "<<Rect.getArea ()<<endl;// Print the area of the object. return0; } 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. The different access types according to who can access them in the following way: Access public Protected private Same class yes Yes Yes Derived Yes Yes No Classes Outside Yes No No Classes
  • 31. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 29 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. Type of Inheritance: When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. • Public Inheritance: When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the class. • Protected Inheritance: When deriving from a protected base class, public and protected members of the base class become protected members of the derived class. • Private Inheritance: When deriving from a private base class, public and protected members of the base class become private members of the derived 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 as shown above. Let us try the following example: Sample Program: 1. Write a C++ program to implement Multiple Inheritance by using Shape and PaintCost as base class and Rectangle as derived class, then use appropriate function to find the cost calculation for the total area. #include<iostream> Usingnamespace std; class Shape // Base class Shape { public: void setWidth(int w) { width= w;
  • 32. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 30 } voidsetHeight(int h) { height= h; } protected: int width; int height; }; classPaintCost { public: intgetCost(int area) { return area *70; } }; classRectangle:publicShape,publicPaintCost // Derived class { public: intgetArea() { return(width * height); } }; int main(void) { RectangleRect; int area; Rect.setWidth(5); Rect.setHeight(7); area=Rect.getArea(); cout<<"Total area: "<<Rect.getArea()<<endl;// Print the area of the object. cout<<"Total paint cost: $"<<Rect.getCost(area)<<endl;// Print the total cost of painting return0; } Output: Total area: 35 Total paint cost: $2450
  • 33. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 31 Lab Exercise: 1. Write a C++ program to calculate the percentage of a student using multi-level inheritance. Accept the marks of three subjects in base class. A class will derived from the above mentioned class which includes a function to find the total marks obtained and another class derived from this class which calculates and displays the percentage of student. Extra Questions: 1. Write a C++ program with 2 base class named animals and birds. Derive from those base class and print any 3 animals and birds in derived class. 2. Write a C++ program to implement the following and give a brief description about the identified inheritance :
  • 34. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 32 Result: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 35. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 33 Date: PROGRAMS USING VIRTUAL FUNCTIONS Exercise 7 Virtual Function: A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function. The selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. Once a member function is declared as a virtual function in a base class, it becomes virtual in every class derived from that base class. In other words, it is not necessary to use the keyword virtual in the derived class while declaring redefined versions of the virtual base class function.
  • 36. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 34 Sample Program: 1. Write a C++ program to implement virtual function fun() in Class A, B and C #include<iostream> using namespace std; class A { public: virtual void fun() { cout<<"n A::fun() called ";} }; class B: public A { public: void fun() { cout<<"n B::fun() called "; } }; class C: public B { public: void fun() { cout<<"n C::fun() called "; } }; int main() { C c; // An object of class C
  • 37. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 35 B *b = &c; // A pointer of type B* pointing to c b->fun(); // this line prints "C::fun() called" getchar(); return 0; } Pure Virtual Functions and Abstract Classes in C++ Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class. For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape, but we know every derived class must have implementation of draw(). Similarly an Animal class doesn’t have implementation of move() (assuming that all animals move), but all animals must know how to move. We cannot create objects of abstract classes. A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration. See the following example. Sample Program: 1. Write a C++ program to implement pure virtual function fun() by using Base class and Derived Class. #include<iostream> using namespace std; class Base { int x; public: virtual void fun() = 0; int getX() { return x; } }; // This class inherits from Base and implements fun() class Derived: public Base { int y; public: void fun() { cout << "fun() called"; } }; int main(void)
  • 38. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 36 { Derived d; d.fun(); return 0; } Output: fun() called Lab Exercise: 1. Create a base class shape. Use this class to store two double type values that could be used to compute area of figures. Derive two specific classes called triangle and rectangle from the base shape. Add to the base a member function getdata() to initialize base class data member and another member function display_area() to compute and display the area of figures. Make display_area() as a virtual function and redefine it the derived class to suit their requirements. Extra Questions: 1. Consider an example of a book shop which sells book and video tapes. These two classes are inherited from the base class called media. The media class has command data members such as title and publication. The book class has data members for storing number of pages in book and tape class has the playing time in a tape. Each class will have member function such as read () and show () in the base class, these members have to be defined as virtual functions. 2. Write a program which models the class hierarchy for the book and process the objects of these classes using pointers to the base class.
  • 39. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 37 Results: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 40. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 38 Date: Programs Using Functions and Class Templates Exercise 8 Templates A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. Templates can be represented in two ways: • Function templates • Class templates Function Templates: We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values. Class Template: We can define a template for a class. For example, a class template can be created for the array class that can accept the array of various types such as int array, float array or double array. Function Template • Generic functions use the concept of a function template. Generic functions define a set of operations that can be applied to the various types of data.
  • 41. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 39 • The type of the data that the function will operate on depends on the type of the data passed as a parameter. • For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats. • A Generic function is created by using the keyword template. The template defines what function will do. Syntax of Function Template template < class Ttype> ret_type func_name(parameter_list) { // body of function. } Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration. Simple Program: 1. Write a simple C++ program for function template #include <iostream> using namespace std; template<class T> T add(T &a,T &b) { T result = a+b; return result; } int main() { int i =2;
  • 42. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 40 int j =3; float m = 2.3; float n = 1.2; cout<<"Addition of i and j is :"<<add(i,j); cout<<'n'; cout<<"Addition of m and n is :"<<add(m,n); return 0; } Function Templates with Multiple Parameters We can use more than one generic type in the template function by using the comma to separate the list. Syntax template<class T1, class T2,.....> return_type function_name (arguments of type T1, T2....) { // body of function. } In the above syntax, we have seen that the template function can accept any number of arguments of a different type. Simple Program: 1. Write a C++ program to implement template function which accepts any number of arguments of different type #include <iostream> using namespace std; template<class X,class Y> void fun(X a,Y b) { std::cout << "Value of a is : " <<a<< std::endl; std::cout << "Value of b is : " <<b<< std::endl;
  • 43. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 41 } int main() { fun(15,12.3); return 0; } CLASS TEMPLATE Class Template can also be defined similarly to the Function Template. When a class uses the concept of Template, then the class is known as generic class. Syntax template<class Ttype> class class_name { } Ttype is a placeholder name which will be determined when the class is instantiated. We can define more than one generic data type using a comma-separated list. The Ttype can be used inside the class body. Now, we create an instance of a class class_name<type> ob; where class_name: It is the name of the class. type: It is the type of the data that the class is operating on. ob: It is the name of the object. Sample Program: 1. Write a C++ program to implement class template for addition of two numbers. #include <iostream> using namespace std; template<class T> class A
  • 44. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 42 { public: T num1 = 5; T num2 = 6; void add() { std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl; } }; int main() { A<int> d; d.add(); return 0; } Output: Addition of num1 and num2: 11 In the above example, we create a template for class A. Inside the main() method, we create the instance of class A named as, 'd'. CLASS TEMPLATE WITH MULTIPLE PARAMETERS We can use more than one generic data type in a class template, and each generic data type is separated by the comma. Syntax template<class T1, class T2, ......> class class_name { // Body of the class. } Sample Program: 1. Write a C++ program to implement class template contains two generic data types. #include <iostream> using namespace std; template<class T1, class T2> class A {
  • 45. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 43 T1 a; T2 b; public: A(T1 x,T2 y) { a = x; b = y; } void display() { std::cout << "Values of a and b are: " << a<<" ,"<<b<<std::endl; } }; int main() { A<int,float> d(5,6.5); d.display(); return 0; } Output: Values of a and b are : 5,6.5 Lab Exercise: 1. Write a C++ program to swap two numbers using function templates. Extra Question: 1. Write a C++ program to find the largest between numbers using the Function Template. 2. Write a C++ program to perform Simple calculator operations using Class template.
  • 46. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 44 Result: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 47. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 45 Date: Files and Streams Exercise 9 Files Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output of a program in a file and to perform various operations on it. A stream is an abstraction that represents a device on which operations of input and output are performed. A stream can be represented as a source or destination of characters of indefinite length depending on its usage. In C++ we have a set of file handling methods. These include ifstream, ofstream, and fstream. These classes are derived from fstrembase and from the corresponding iostream class. These classes, designed to manage the disk files, are declared in fstream and therefore we must include fstream and therefore we must include this file in any program that uses files. In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream. • ofstream: This Stream class signifies the output file stream and is applied to create files for writing information to files • ifstream: This Stream class signifies the input file stream and is applied for reading information from files • fstream: This Stream class can be used for both read and write from/to files. All the above three classes are derived from fstream base and from the corresponding iostream class and they are designed specifically to manage disk files. C++ provides us with the following operations in File Handling: • Creating a file: open() • Reading data: read() • Writing new data: write() • Closing a file: close() Opening a File First operation performed on an object of one of these classes is to associate it to a real file. This procedure is known to open a file. We can open a file using any one of the following methods. 1. First is bypassing the file name in constructor at the time of object creation. 2. Second is using the open() function. To open a file use open() function
  • 48. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 46 Syntax void open(const char* file_name,ios::openmode mode); Here, the first argument of the open function defines the name and format of the file with the address of the file. The second argument represents the mode in which the file has to be opened. Example fstream new_file; new_file.open(“newfile.txt”, ios::out); Sample Program: 1. Write C++ FileStream program to create or open a file using the open() function #include<iostream> #include <fstream> using namespace std; int main() { fstream new_file; new_file.open("new_file",ios::out); if(!new_file) { cout<<"File creation failed"; } else { cout<<"New file created"; new_file.close(); // Step 4: Closing file } return 0; } 2. Write a C++ FileStream program to write to a file #include <iostream> #include <fstream> using namespace std; int main () { ofstream filestream("testout.txt"); if (filestream.is_open())
  • 49. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 47 { filestream << "Welcome to javaTpoint.n"; filestream << "C++ Tutorial.n"; filestream.close(); } else cout <<"File opening is fail."; return 0; } 3. Write a C++ FileStream program to read from a file #include <iostream> #include <fstream> using namespace std; int main () { string srg; ifstream filestream("testout.txt"); if (filestream.is_open()) { while ( getline (filestream,srg) ) { cout << srg <<endl; } filestream.close(); } else { cout << "File opening is fail."<<endl; } return 0; } 4. Write a C++ FileStream program to close a File It is simply done with the help of close() function. Syntax: File Pointer.close() #include <iostream> #include <fstream> using namespace std; int main() {
  • 50. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 48 fstream new_file; new_file.open("new_file.txt",ios::out); new_file.close(); return 0; } Lab Exercise: 1. Write a program that opens a file, reads its contents, and changes any vowels it finds to a ‘#’ symbol and finally close a file Extra Question: 1. Write a program that merges the numbers in two files and writes all the numbers into a third file. Your program takes input from two different files and writes its output to a third file. Each input file contains a list of numbers of type int in sorted order from the smallest to the largest. After the program is run, the output file will contain all the numbers in the two input files in one longer list in sorted order from smallest to largest. Your program should define a function that is called with the two input-file streams and the output-file stream as three arguments.
  • 51. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 49 Result: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty
  • 52. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 50 Date: Exception Handling Exercise 10 Exception Handling Exception Handling in C++ is a process to handle runtime errors. We perform exception handling so the normal flow of the application can be maintained even after runtime errors. In C++, exception is an event or object which is thrown at runtime. All exceptions are derived from std::exception class. It is a runtime error which can be handled. If we don't handle the exception, it prints exception message and terminates the program. In C++, we use 3 keywords to perform exception handling: • try • catch, and • throw Why Exception Handling? Following are main advantages of exception handling over traditional error handling. 1) Separation of Error Handling code from Normal Code: In traditional error handling codes, there are always if else conditions to handle errors. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try catch blocks, the code for error handling becomes separate from the normal flow. 2) Functions/Methods can handle any exceptions they choose: A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller. In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it)
  • 53. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 51 3) Grouping of Error Types: In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types. Rethrowing Exceptions: • Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no exception. • This causes current exception to be passed on to an outer try/catch sequence. An exception can only be rethrown from within a catch block. • When an exception is rethrown, it is propagated outward to the next catch block Sample Program: 1. Write a C++ program to rethrow an exception. #include <iostream> using namespace std; void MyHandler() { try { throw “hello”; } catch (const char*) { cout <<”Caught exception inside MyHandlern”; throw; //rethrow char* out of function } } int main() { cout<< “Main start”; try { MyHandler(); } catch(const char*) { cout <<”Caught exception inside Mainn”; } cout << “Main end”; return 0;}
  • 54. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 52 Exception Handling in C++ Following is a simple example to show exception handling in C++. The output of program explains flow of execution of try/catch blocks. Sample Program: 1. Write a simple C++ program to show exception handling. #include <iostream> using namespace std; int main() { int x = -1; cout << "Before try n"; try { cout << "Inside try n"; if (x < 0) { throw x; cout << "After throw (Never executed) n"; } } catch (int x ) { cout << "Exception Caught n"; } cout << "After catch (Will be executed) n"; return 0; } Output Before try Inside try Exception Caught After catch (Will be executed) 2. Write a C++ program to throw exception for divide by zero error. #include <iostream> using namespace std; float division(int x, int y) { if( y == 0 ) { throw "Attempted to divide by zero!"; }
  • 55. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 53 return (x/y); } int main () { int i = 25; int j = 0; float k = 0; try { k = division(i, j); cout << k << endl; }catch (const char* e) { cerr << e << endl; } return 0; } User Defined Exceptions The new exception can be defined by overriding and inheriting exception class functionality. The C++ std::exception class allows us to define objects that can be thrown as exceptions. This class has been defined in the <exception> header. The class provides us with a virtual member function named what. This function returns a null-terminated character sequence of type char *. We can overwrite it in derived classes to have an exception description. Sample Program: 1. Write a C++ program to create and throw a user defined exception if the condition "divide by zero" occurs. #include <iostream> #include <exception> using namespace std; class MyException : public exception{ public: const char * what() const throw() { return "Attempted to divide by zero!n"; } }; int main() {
  • 56. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 54 try { int x, y; cout << "Enter the two numbers : n"; cin >> x >> y; if (y == 0) { MyException z; throw z; } else { cout << "x / y = " << x/y << endl; } } catch(exception& e) { cout << e.what(); } } Lab Exercise: 1. Write a C++ program that converts 24-hour time to 12-hour time. The following is a sample output: Enter time in 24-hour notation: 13:07 That is the same as 1:07 PM Again?(y/n) y Enter time in 24-hour notation: 10:15 That is the same as 10:15 AM Again?(y/n) y
  • 57. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 55 You will define an exception class called TimeFormatMistake. If the user enters an illegal time, like 10:65 or even gibberish like 8&*68, then your program will throw and catch a TimeFormatMistake. Extra Question: 1. Write a program to detect and throw an exception if the condition "divide by zero" occurs by using appropriate try, catch and throw blocks.
  • 58. Department of Computer Science and Engineering 20CSG02 – PROGRAMMING IN C++ LABORATORY (2022-23) 56 Result: S.NO DESCRIPTION WEIGHTAGE MARK AWARDED 1 Algorithm and Program Implementation 10 2 Experimental Results And Analysis 10 3 Viva-voce 10 Total 30 Signature of the Faculty