OOP Through C++ Lab Manual
OOP Through C++ Lab Manual
(Autonomous)
(Affiliated to Osmania University, Hyderabad, Approved by A.I.C.T.E.)
9-5-81, Ibrahimbagh , Hyderabad - 500 031 (T.S.)
www.vce.ac.in
LAB MANUAL
(Student Manual)
For
BE EEE II-SEMESTER
2023-24
9 Programs to demonstrate
function overloading.
Programs to demonstrate
10 operator overloading.
! exclamation : colon
/ slash ~ equivalency-tilde
Keywords:
Keywords are those words, whose meaning is already known to the C++ compiler i.e. they are
predefined words. The keywords cannot be used as variable names.
C++ -Compilers
• Borland Turbo C/ Turbo C
• Tiny C Compiler
• Portable C Compiler
• GCC
• MinGW / GCC
• Borland c++
• Dev C++
• Embracadero
• Clang
• Visual C++
• Intel C++
• Code Block
Online Compilers
• Programiz: https://www.programiz.com/c-programming/online-compiler/
. GDB : https://www.onlinegdb.com/online_c_compiler
Web learning
https://www.geeksforgeeks.org/c-plus-plus/
https://leetcode.com/discuss/study-guide/
Shortcut Keys for Turbo C++
F1 For Help
F2 Save
F3 Open
F4 Go to Curser
F5 Zoom
F6 Next
F7 Trace Into
F8 Step Over
F10 Make
Alt+X Menu
Alt+Bksp Quit
Shift+Alt+Bksp Undo
Shift+Del Redo
Alt + F9 Compile
Ctrl+ F9 Run Code
Ctrl + Y Delete Line
Ctrl + Ins Copy
Shift + Del Cut
Shift + Ins Paste
Windows Exit
Ctrl + S Save
Alt + Bksp Undo
Alt + X Quit
Alt+F5 To check output
Alt+F For menu bar options
Alt+F3 Close
Introduction Programs:
➢ In the Turbo C++ compiler, all the header files should be include with .h Ex
#include<iostream.h>. In other compilers .h not required like #include<iostream> is
enough
➢ In the Turbo C++ compiler, cin>> or cout<< is enough for input or output
operations(std:: or using namespace std not required)
INPUT/OUTPUT
• Use the C++ extraction operator (>>) to extract data from the input stream,
such as cin. cin is a standard input stream, which is usually the keyboad.
•
• Syntax: cin >> input variable;
Example: int x, y;
•
cin >>x>>y; //Accept two integer numbers entered from the keyboard. The
numbers are separated by at least one space.
• Use the C++ extraction operator (<<) to insert data into an output stream.
You can use the cout output stream. cout is a standard output stream, which
is a screen.
#include <iostream.h>
//using namespace std;
void printUptoN(int n) {
if (n > 1)
printUptoN(n - 1);
cout << n << " ";
}
int main() {
int n;
cout << "Enter the upper limit= ";
cin >> n;
cout << "First " << n << " natural numbers are : ";
printUptoN(n);
return 0;
}
Output: Enter the upper limit= 10
First 10 natural numbers are : 1 2 3 4 5 6 7 8 9 10
1.d) Write a program to print the square root of the given number
#include <iostream.h>
#include <cmath.h>
int main()
{
double x;
cout << "Input number:" << endl;
cin >> x;
double sqrt_x = sqrt(x);
cout << "Sq. Root of " << x;
cout << " is: " << sqrt_x << endl;
}
Outpu: Input number:
15
Sq. Root of 15 is: 3.87298
1.e) Write a program to print the sum N natural numbers
#include <iostream.h>
int main() {
int n;
int sum = 0;
cout << "Input Number limit:" << endl;
cin >> n;
for (int i = 0; i <= n; ++i) // Local Decl.
sum = sum + i;
cout << "Sum of " << n ;
cout << " numbers is: " << sum << endl;
}
Output:
Input Number limit:
10
Sum of 10 numbers is: 55
1.f) Write a program to check the given number is prime or not.
#include <iostream.h> cout << n << " is not a prime
//using namespace std; number";
int i, n; }
if (n == 0 || n == 1) end:
{ return 0;
Roll number: 1
Name: Sachin
Marks: 90
Roll number: 2
Name: dravid
Marks: 85
Roll number: 3
Name: dhoni
Marks: 92
2.b) Write a C++ Program to Add Two Complex Numbers using Class.
#include<iostream>
//using namespace std;
class Complex{
public:
int real;
int imag;
void setvalue()
{
cin>>real;
cin>>imag;
}
void display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
void sum(Complex c1, Complex c2)
{
real=c1.real+c2.real;
imag=c1.imag+c2.imag;
}
};
int main()
{
Complex c1,c2,c3;
cout<<"Enter real and imaginary part of first complex number"<<endl;
c1.setvalue();
cout<<"Enter real and imaginary part of second complex number"<<endl;
c2.setvalue();
cout<<"Sum of two complex numbers is"<<endl;
c3.sum(c1,c2);
c3.display();
return 0;
}
Output:
Enter real and imaginary part of first complex number
23
Enter real and imaginary part of second complex number
35
Sum of two complex numbers is
5+8i
2.C) Write C++ program to read, add and display matrix using class
#include<iostream>
#include<conio.h>
//using namespace std;
class matrix
{
int a;
int b;
int A[3][3];
public:
void readmatrix();
void displaymatrix();
};
void matrix::readmatrix()
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
cout<<"A["<<i<<"]["<<j<<"] : ";
cin>>A[i][j];
}
}
}
void matrix::displaymatrix()
{
cout<<"output matrix";
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
cout<<" "<<A[i][j]+A[i][j];
}
cout<<endl;
}
}
int main()
{
matrix m;
m.readmatrix();
m.displaymatrix();
getch();
return(0);
}
Output
A[1][1] : 2
A[1][2] : 3
A[1][3] : 4
A[2][1] : 5
A[2][2] : 6
A[2][3] : 7
A[3][1] : 8
A[3][2] : 9
A[3][3] : 10
Output matrix
468
10 12 14
16 18 20
3. Encapsulation
For example, let's consider a class named "BankAccount". This class may contain private
data such as "accountNumber", "balance", and "interestRate", and behavior such as
"deposit()", "withdraw()", and "calculateInterest()".
Encapsulation allows us to protect the data of the bank account object, so that it can
only be accessed through well-defined methods, such as "getBalance()" and "deposit()".
This ensures that the internal state of the bank account is maintained correctly and
prevents unauthorized access to its data.
Inheritance is the process by which one class (the subclass) derives the properties and
methods of another class (the superclass). Inheritance allows subclasses to reuse the
code of their superclasses, thereby reducing code duplication and promoting code
reuse. Subclasses can also add their own unique properties and behaviors to the
inherited code.
For example, let's consider a class hierarchy consisting of a superclass named "Animal" and
two subclasses named "Cat" and "Dog". The Animal class may contain properties such as
"name" and "age", and methods such as "eat()" and "sleep()". The Cat subclass can inherit
these properties and methods from the Animal class and add its own unique properties and
behaviors, such as "meow()" and "climb()". Similarly, the Dog subclass can inherit from the
Animal class and add its own unique properties and behaviors, such as "bark()" and "fetch()".
Abstraction is the practice of focusing on the essential features of an object and ignoring
the non-essential ones. This allows for the creation of simple and easy-to-use interfaces
for complex systems.
For example, consider a car. A customer doesn't need to know how the engine works or
how the transmission shifts gears. Instead, they only need to know how to start and
drive the car.
In C++, abstraction can be achieved using abstract classes. An abstract class is a class
that cannot be instantiated but can be inherited by other classes. It defines a set of
methods that must be implemented by any class that inherits from it but does not
implement those methods itself.
#include <iostream.h>
//using namespace std;
class Vehicle
{
public:
virtual void start() = 0; // pure virtual method
virtual void stop() = 0; // pure virtual method
};
class Car : public Vehicle
{
public:
void start()
{
cout << "Starting..." << endl;
}
void stop()
{
cout << "Stopping..." << endl;
}
};
int main()
{
Car myCar;
myCar.start();
myCar.stop();
return 0;
}
Output:
Starting...
Stopping...
Allocating memory
There are two ways that memory gets allocated for data storage:
#include<string.h>
class Student {
private:
int rollNo;
char name[10];
int marks;
public:
Student() {
objectCount++;
void getdata() {
void putdata() {
cout<<endl;
};
int Student::objectCount = 0;
int main(void) {
Student s1;
s1.getdata();
s1.putdata();
Student s2;
s2.getdata();
s2.putdata();
Student s3;
s3.getdata();
s3.putdata();
cout << "Total objects created = " << Student::objectCount << endl;
return 0;
5.A) Write a C++ program for the dynamic allocation of memory for the
elements
#include<iostream>
int main() {
int x, n;
cin >>n;
cout << "Enter " << n << " items" << endl;
return 0;
}
Output:
Enter 5 items
78942
You entered: 7 8 9 4 2
5.B) Write a program for the dynamic allocation of memory for the array
elements
#include <iostream.h>
//using namespace std;
int main(void)
{
int x;
int *array{ new int[5]{ 10, 7, 15, 3, 11 } };
cout << "Array elements: " << endl;
for (x = 0; x < 5; x++) {
cout << array[x] << endl;
}
return 0;
}
Output:
Array elements:
10
7
15
3
11
6. Programs on string manipulations.
6.a) String Length: std::string::length
The string length function calculates the length (number of characters) of a string.
#include <iostream.h>
#include <string>
int main() {
std::string str = "Hello, World!";
int length = str.size(); // Returns the length of the string, which is 13
std::cout << "The length of the string is: " << length << std::endl;
return 0;
}
Output:
The string copy function copies a string from a source location to a destination
#include <iostream.h>
#include <cmath>
int main() {
char source[] = "Hello, World!"; // Source string
char destination[20]; // Destination character array
std::strcpy(destination, source); // Copy the source string to the destination
std::cout << "Source string: " << source << std::endl;
std::cout << "Copied string: " << destination << std::endl;
return 0;
}
Output:
The string comparison function compares two strings lexicographically and returns an integer
representing the result.
#include <iostream.h>
#include <string>
int main() {
std::string str1 = "apple";
std::string str2 = "banana";
int result = str1.compare(str2);
if (result == 0) {
std::cout << "The strings are equal." << std::endl;
} else if (result < 0) {
std::cout << "The string str1 is less than str2." << std::endl;
} else {
std::cout << "The string str1 is greater than str2." << std::endl;
}
return 0;
}
Output:
#include <iostream.h>
//using namespace std;
int main() {
string str = "123";
int num = stoi(str);
cout << num << endl;
return 0;
}
Output:
123
#include <iostream.h>
//using namespace std;
int main() {
string str = "3.14";
double num = stod(str);
cout << num << endl;
return 0;
}
Output:
3.14
6.f) Numeric to String Conversion: std::to_string
#include <iostream.h>
#include <string>
//using namespace std;
int main() {
int num = 42;
string str = to_string(num);
cout << str << endl;
return 0;
}
Output:
42
#include <iostream.h>
#include <string>
//using namespace std;
int main() {
string str1 = "Hello";
string str2 = " World!";
string result = str1 + str2;
cout << result << endl;
return 0;
}
Output:
Hello World!
The string substring function extracts a substring from a string, starting at a specified position
and with a specified length.
#include <iostream.h>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string substr = str.substr(7, 5); // Extracts "World" from the original string
std::cout << "The substring is: " << substr << std::endl;
return 0;
}
Output:
The string padding function pads a string with a specified character or space to a certain
width.
#include <iostream.h>
#include <string>
//using namespace std;
int main() {
string str = "Hello";
cout << setw(10) << setfill(' ') << str << endl;
return 0;
}
Output:
Hello
#include <iostream.h>
#include <string>
//using namespace std;
int main() {
string str = "Hello, World!";
str.replace(7, 5, "Universe"); // Replaces the substring "World" with "Universe"
cout << str << endl;=
return 0;
}
Output:
Hello, Universe!
7. Friend function
7.A) Write a Program to find Maximum out of Two Numbers using friend
function.
Note: Here one number is a member of one class and the other number is member
of some other class.
#include<iostream>
class ABC;
class XYZ
int x; public:
void setvalue(int i)
x=i;
};
class ABC
int a; public:
void setvalue(int i)
a=i;
};
if(m.x>=n.a)
cout<<m.x;
else
cout<<n.a;
int main()
max(xyz,abc);
return 0;
Output:
20
7.B) Write a Program to swap private data members of classes named as class_1,
class_2 using friend function.
#include<iostream>
class class_2;
class class_1
void indata(int a)
value1=a;
void display(void)
cout<<value1<<"\n";
};
class class_2
{
int value2; public:
void indata(int a)
value2=a;
void display(void)
cout<<value2<<"\n";
};
int main()
C1.indata(100);
C2.indata(200);
C1.display();
C2.display(); return 0;
Output:
100 200
200 100
7.C) Write a Program to design a class complex to represent complex numbers. The
complex class shuold use an external function (use it as a friend function) to add two
complex numbers.The function should return an object of type complex representing
the sum of two complex numbers.
#include<iostream>
//using namespace std;
class complex
{
float x; float y;
public:
void input(float real, float img)
{
x=real; y=img;
}
friend complex sum(complex, complex); void show(complex);
};
complex sum(complex c1, complex c2)
{
complex c3;
c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return (c3);
}
void complex :: show(complex c)
{
cout<<c.x<<"+j"<<c.y<<"\n";
}
int main()
{
complex A,B,C; A.input(3.1, 5.65);
B.input(2.75, 1.2);
C=sum(A,B);
cout<<"A=";
A.show(A);
cout<<"B=";
B.show(B);
cout<<"C=";
C.show(C);
return 0;
}
Output:
A=3.1+j5.65
B=2.75+j1.2
C=5.85+j6.85
8.A) Write a C++ program with simple example of construct
#include <iostream.h>
//using namespace std;
class construct {
public:
int a, b;
construct()
{
a = 10;
b = 20;
}
};
int main()
{
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 0;
}
Output:
a: 10
b: 20
8.B) Write a Program using copy constructor to copy data of an object to
another object.
#include<iostream>
//using namespace std;
class code
{
int id; public:
code(){} code(int a)
{
id = a;
}
code(code & x)
{
id = x.id;
}
void display(void)
{
cout<<id;
}
};
int main()
{
code A(100);
code B(A);
code C = A;
code D;
D = A;
cout<<"\n id of A:";
A.display();
cout<<"\n id of B:";
B.display();
cout<<"\n id of C:";
C.display();
cout<<"\n id of D:";
D.display();
return 0;
}
Output:
id of A:100
id of B:100
id of C:100
id of D:100
8.C) Write a Program to allocate memory dynamically for an objects of a
given class using class’s constructor.
#include<iostream.h>
#include<cstring>
//using namespace std;
class String
{
char *name; int length;
public:
String()
{
length = 0;
name = new char[length +1];
}
String (char *s)
{
length = strlen(s);
name= new char[length + 1]; strcpy(name, s);
}
void display(void)
{
cout<<name<<"\n";
}
void join(String &a, String &b);
};
void String :: join (String &a, String &b)
{
length = a.length + b.length; delete name;
name = new char [length + 1];
strcpy(name,a.name); strcat(name, b.name);
};
int main()
{
char *first = "Joseph";
String name1(first), name2("Louis "), name3("Lagrange"),s1,s2; s1.join(name1,
name2);
s2.join(s1, name3); name1.display(); name2.display(); name3.display(); s1.display();
s2.display();
return 0;
}
Output:
Joseph JosephLouis
Louis JosephLouis Lagrange
Lagrange
8.D) Write a C++ program to demonstrate the number of times constructor and
destructors are called
#include <iostream.h>
//using namespace std;
static int Count = 0;
class Test {
public:
Test()
{
Count++;
cout << "No. of Object created: " << Count << endl;
}
// User-Defined Destructor
~Test()
{
cout << "No. of Object destroyed: " << Count
<< endl;
Count--;
}
};
int main()
{
Test t, t1, t2, t3;
return 0;
}
9.A) Write a C++ program of function overloading when number of
arguments vary.
#include <iostream.h>
//using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C;
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55
9.B) Write a C++ program of function overloading with different types of
arguments.
#include<iostream>
//using namespace std;
int mul(int,int);
float mul(float,int);
int mul(int a,int b)
{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}
Try the programs with different function overloading.
class ComplexNumber {
private:
int real;
int imaginary;
public:
ComplexNumber(int real, int imaginary)
{
this->real = real;
this->imaginary = imaginary;
}
void print() { cout << real << " + i" << imaginary; }
ComplexNumber operator+(ComplexNumber c2)
{
ComplexNumber c3(0, 0);
c3.real = this->real + c2.real;
c3.imaginary = this->imaginary + c2.imaginary;
return c3;
}
};
int main()
{
ComplexNumber c1(3, 5);
ComplexNumber c2(2, 4);
ComplexNumber c3 = c1 + c2;
c3.print();
return 0;
}
Output: 5 + i9
Try the programs with different operator overloading.
11.A) Write a C++ program to demonstrate the use of try, catch and throw in exception
handling
#include <iostream.h>
#include <stdexcept>
//using namespace std;
int main()
{
try {
int numerator = 10;
int denominator = 0;
int res;
if (denominator == 0) {
throw runtime_error(
"Division by zero not allowed!");
}
return 0;
}
Output:
Exception Division by zero not allowed!
11.B) Write a C++ program to demonstrate Multiple Catch Block Exception Program
#include <iostream.h>
//using namespace std;
float divide(int x, int y) {
if (y == 0) {
throw y;
} else if (y < 0) {
throw "Negative Input";
}
return (x / y);
}
int main() {
int i, result;
cout << "Enter the Number :";
cin>>i;
try {
result = divide(100, i);
cout << result << endl;
} //catch block
catch (int exception_value) {
cout << "Exception Occurred : Exception Value : " << exception_value;
} catch (const char* excpection_str) {
cout << "Exception Occurred : Exception Value : " << excpection_str;
}
return 0;
}
Output:
Enter the Number :5
20
Enter the Number :0
Exception Occurred : Exception Value : 0
Enter the Number :-2
Exception Occurred : Exception Value : Negative Input