0% found this document useful (0 votes)
17 views18 pages

C++ Class Experiments: OOP Concepts

The document outlines a series of C++ programming experiments focusing on various object-oriented programming concepts such as encapsulation, operator overloading, friend functions, templates, file handling, and polymorphism. Each experiment includes an aim, theory, code implementation, reference, and conclusion, demonstrating the practical application of these concepts in creating modular and reusable code. The experiments illustrate how to design classes, manage data, and utilize C++ features effectively.

Uploaded by

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

C++ Class Experiments: OOP Concepts

The document outlines a series of C++ programming experiments focusing on various object-oriented programming concepts such as encapsulation, operator overloading, friend functions, templates, file handling, and polymorphism. Each experiment includes an aim, theory, code implementation, reference, and conclusion, demonstrating the practical application of these concepts in creating modular and reusable code. The experiments illustrate how to design classes, manage data, and utilize C++ features effectively.

Uploaded by

harshk4525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

23/EE/119

EXPERIMENT -16
Aim: Write a C++ program to print the area of a rectangle by creating a class named Area
having two functions. The first named setDim() takes the length and breadth of the
rectangle, and the second named getArea() returns the area of the rectangle.
Theory: This experiment is a fundamental example of Object-Oriented Programming,
focusing on the principle of encapsulation. By creating a class named `Area`, we bundle the
data (length and breadth) with the functions that operate on it (`setDim` and `getArea`). This
practice hides the internal details from the main part of the program. It provides a clean and
controlled interface, preventing direct, uncontrolled access to the data members, which
makes the code more robust, organized, and easier to manage.
Code:
#include <iostream>
using namespace std;
class Area{
float len;
float br;
public:
void setDim(float a,float b){
len=a;
br=b;
}
float getarea(){
return len*br;
}

};

Reference:
Conclusion: The program successfully implemented the `Area` class to encapsulate the
properties and behavior of a rectangle. The `setDim()` function provides a controlled way to
set the object's data, while `getArea()` provides the calculated result. This demonstrates a
clean separation of concerns, making the code modular, easy to understand, and reusable.
The main function simply uses the object's public interface without needing to manage the
internal data, showcasing the core benefit of encapsulation.

42
23/EE/119

Output:

43
23/EE/119

EXPERIMENT -17
Aim: Write a program to find the greatest of two given numbers in two different classes
using a friend function.
Theory: A friend function in C++ is a non-member function that is granted special access to
the private and protected members of a class. This is an exception to the rule of
encapsulation. In this experiment, we need to compare private data from two separate,
unrelated classes. Since a standard function cannot access this private data, and a member
function of one class cannot access the private data of another, a friend function is the ideal
solution. It acts as a trusted "friend" to both classes, allowing it to bridge the gap between
them and operate on their internal data. A forward declaration is necessary to inform the
compiler about the existence of a class before it is fully defined.
Code:
#include <iostream>
using namespace std;
class ClassC;
class ClassB{
private:
int numB;
public:
ClassB(int n):numB(n) {}
friend void findmax(ClassB B ,ClassC c);
};
class ClassC{
private:
int numC;
public:
ClassC(int n):numC(n){}
friend void findmax(ClassB b,ClassC c);
};
void findmax(ClassB b,ClassC c){
cout<<"Comparing:"<<[Link]<<" from ClassB and "<<[Link]<<" from
ClassC."<<endl;

44
23/EE/119

if([Link]>[Link]){
cout<<[Link]<<" is the greater number."<<endl;
}
else if([Link]>[Link]){
cout<<[Link]<<" is the greater number."<<endl;
}
else{
cout<<"Numbers are equal."<<endl;
}
}

Reference: GeeksForGeeks: friend function.


Conclusion: The program successfully utilized a friend function to find the greater of two
numbers stored in the private sections of two different classes. This demonstrates the
unique capability of friend functions to bypass normal access restrictions, providing a clean
solution for operations that require access to the internal state of multiple classes
simultaneously. While powerful, this feature should be used judiciously as it can weaken the
encapsulation that is central to object-oriented design.
Output:

45
23/EE/119

EXPERIMENT-18
Aim: Implement a class string containing the following functions: Overload + operator to
carry out the concatenation of strings. Overload = operator to carry out string copy.
Overload <= operator to carry out the comparison of strings. Function to display the length
of a string. Function tolower() to convert upper case letters to lower case. - Function
toupper() to convert lower case letters to upper case.
Theory: This experiment focuses on operator overloading and building a custom class to
mimic the behaviour of a standard string. Operator overloading allows you to redefine how
C++ operators (like +, =, <=) work with objects of your own classes. Instead of using a
function call like str3 = [Link](str2), you can use the more intuitive syntax str3 =
str1 + str2. To achieve this, you create special member functions with names like operator+
or operator=. This program will create a String class that encapsulates a character array and
overloads several operators to provide familiar, easy-to-use string manipulation capabilities.
Code:
#include <iostream>
#include <cstring>
using namespace std;

class String {
char str[100];
public:
String() { strcpy(str, ""); }

String(const char s[]) { strcpy(str, s); }

// Overload + operator for concatenation


String operator+(String s) {
String temp;
strcpy([Link], str);
strcat([Link], [Link]);
return temp;
}

46
23/EE/119

// Overload = operator for copy


void operator=(String s) {
strcpy(str, [Link]);
}

// Overload <= operator for comparison


bool operator<=(String s) {
return (strcmp(str, [Link]) <= 0);
}

// Function to return length


int length() {
return strlen(str);
}

// Convert to lowercase
void toLower() {
for (int i = 0; str[i]; i++)
str[i] = tolower(str[i]);
}

// Convert to uppercase
void toUpper() {
for (int i = 0; str[i]; i++)
str[i] = toupper(str[i]);
}

// Display function
void display() {
cout << str << endl;

47
23/EE/119

}
};

Reference: w3schools: overload operators


Conclusion: This program successfully demonstrates how to build a custom class with
overloaded operators to create an intuitive and powerful interface. By overloading `+`, `=`,
and `<=`, the `String` class objects can be manipulated with the same ease as built-in types.
The implementation of member functions for length and case conversion further
encapsulates string-related logic within the class. This experiment is an excellent example of
how C++ allows developers to create complex, user-friendly types that are both efficient and
easy to work with.
Output:

48
23/EE/119

EXPERIMENT -19
Aim: Write a program to overload the unary increment (++) operator.
Theory: Operator overloading allows us to define a custom behavior for an operator when
used with a class object. The unary increment operator (++) has two forms: prefix (++obj)
and postfix (obj++), which require different function signatures for overloading. The prefix
version modifies the object's value and then returns the modified object. The postfix
version, however, must save the object's original state, modify the object, and then return
the saved (unmodified) state. To differentiate the postfix signature from the prefix one, the
compiler requires the postfix overload function to have a dummy 'int' parameter.
Code:

#include <iostream>
using namespace std;

class Counter {
int value;
public:
Counter() { value = 0; }
Counter(int v) { value = v; }

// Prefix increment
Counter operator++() {
++value;
return *this;
}

// Postfix increment
Counter operator++(int) {
Counter temp = *this;
value++;
return temp;
}

49
23/EE/119

void display() {
cout << "Value: " << value << endl;
}
};

Conclusion: This program successfully demonstrates how to overload both the prefix and
postfix unary increment operators in C++. The key difference in their implementation and
behavior was highlighted: the prefix operator modifies and then returns the object, whereas
the postfix operator returns a copy of the object's original state before performing the
modification. This illustrates how operator overloading can be used to provide intuitive,
standard behaviors for custom user-defined types.
Output:

50
23/EE/119

EXPERIMENT-20
Aim: Write a program to define the function template for calculating the square of given
numbers with different data types.
Theory: A function template is a powerful C++ feature that allows you to write a single,
generic function that can work with different data types. Instead of writing separate
functions like `squareInt()`, `squareFloat()`, and `squareDouble()`, you create a "template" or
blueprint of the function. You use a placeholder type (e.g., `T`) for the data type. When you
call the function with a specific type (like an `int` or a `double`), the compiler automatically
generates the correct version of that function at compile-time. This promotes code
reusability and reduces redundancy, which is a core principle of generic programming.
Code:
#include <iostream>
using namespace std;

// Function template
template <class T>
T calculateSq(T num) {
return num * num;
}

int main() {
int i = 1;
float f = 1.5;
double d = 1.78;

cout << "Square of int: " << calculateSq(i) << endl;


cout << "Square of float: " << calculateSq(f) << endl;
cout << "Square of double: " << calculateSq(d) << endl;

return 0;
}

51
23/EE/119

Reference: GeeksForGeeks: templates


Conclusion: The program successfully demonstrates the use of a function template to
achieve generic programming. A single `calculateSquare` function was able to operate
seamlessly with `int`, `float`, and `double` data types without any changes to its code. This
proves that templates are a highly effective mechanism for writing flexible, reusable, and
type-safe code in C++, eliminating the need to write and maintain multiple, nearly identical
functions for different data types.
Output:

52
23/EE/119

EXPERIMENT-21
Aim: Write a program to read the class object of student info, such as name, age, sex, height,
and weight, from the keyboard and to store them on a specified file using read() and write()
functions. Again, the same file is opened for reading and displaying the contents of the file
on the screen.
Theory: This experiment demonstrates object persistence, which is saving an object's data
from memory to a file so it isn't lost. The Student object, which bundles all its information, is
serialized by copying its raw data, byte-for-byte, directly into a file. To load it, we do
deserialization: reading those bytes back from the file into a new object, restoring its saved
state. This direct-copy method requires using fixed-size data fields, as flexible text types
store their data elsewhere, which prevents this simple copy-paste from working.
Code:

#include <iostream>
#include <fstream>
using namespace std;

class Student {
char name[30], sex[10];
int age;
float height, weight;

public:
void getData() {
cout << "Enter name: ";

[Link](name, 30);
cout << "Enter age: ";
cin >> age;
cout << "Enter sex: ";
cin >> sex;
cout << "Enter height: ";
cin >> height;
cout << "Enter weight: ";

53
23/EE/119

cin >> weight;


[Link]();
}

void showData() {
cout << "\nName: " << name
<< "\nAge: " << age
<< "\nSex: " << sex
<< "\nHeight: " << height
<< "\nWeight: " << weight << endl;
}
};

int main() {
Student s, s2;
fstream file("[Link]", ios::out | ios::binary);

cout << "Enter student details:\n";


[Link]();

// Write object to file


[Link]((char *)&s, sizeof(s));
[Link]();

// Read object from file


[Link]("[Link]", ios::in | ios::binary);
[Link]((char *)&s2, sizeof(s2));
[Link]();

cout << "\nData read from file:\n";

54
23/EE/119

[Link]();

return 0;
}

Reference: GeeksForGeeks: file handling in C++.


Conclusion: This experiment successfully illustrates how to use file handling in C++ to store
and retrieve class objects. It demonstrates how data, such as name, age, sex, height, and
weight, can be written to and read from a file using the write() and read() functions. Thus, it
helps in understanding object serialization and persistent data storage using OOP concepts.
Output:

55
23/EE/119

EXPERIMENT -22
Aim: Create a base class called SHAPE. Use this class to store two double-type values. Derive
two specific classes called TRIANGLE and RECTANGLE from the base class. Add to the base
class, a member function getdata to initialize base class data members, and another
member function display to compute and display the area of figures. Make a virtual function
and redefine this function in the derived classes to suit their requirements. Using these
three classes, design a program that will accept the dimensions of a TRIANGLE or
RECTANGLE interactively and display the area.
Theory: This experiment demonstrates the concept of runtime polymorphism using virtual
functions in C++. A base class Shape stores common attributes like dimensions and defines a
virtual function display() to calculate area. The derived classes Triangle and Rectangle
override this function to compute their specific areas. By using a base class pointer, the
program decides at runtime which display() function to execute, showing the power of
dynamic binding and inheritance in OOР.
Code:
#include <iostream>
using namespace std;

class Shape {
protected:
double a, b;

public:
void getdata() {
cout << "Enter two dimensions: ";
cin >> a >> b;
}

virtual void display() {


cout << "This is a shape.\n";
}
};

56
23/EE/119

class Triangle : public Shape {


public:
void display() override {
cout << "Area of Triangle = " << 0.5 * a * b << endl;
}
};

class Rectangle : public Shape {


public:
void display() override {
cout << "Area of Rectangle = " << a * b << endl;
}
};

Reference: GeeksForGeeks: Polymorphism.


Conclusion: This experiment demonstrates runtime polymorphism using virtual functions in
C++. It shows how a base class pointer can call the correct function from derived classes
dynamically. Thus, it highlights the efficiency and flexibility of inheritance and polymorphism
in object-oriented programming.
Output:

57
23/EE/119

EXPERIMENT-23
Aim: Write a program to illustrate how to define and declare a class template for reading
two data items from the keyboard and to find their sum.
Theory: A class template allows defining a generic class that works with different data types
(like int, float, double, etc.) without rewriting code. By using the template, two data items of
any type can be read from the keyboard, and their sum can be calculated easily.
Code:
#include <iostream>
using namespace std;
template <class T>
class Add {
T n1, n2;

public:
void getData() {
cout << "Enter two numbers: ";
cin >> n1 >> n2;
}

void displaySum() {
cout << "Sum = " << n1 + n2 << endl;
}
};

Reference: GeeksForGeeks : Templates

Conclusion: This experiment shows how class templates make programs more flexible and
reusable. By using templates, a single class can work with multiple data types without
rewriting code. It highlights the concept of generic programming and improves efficiency in
C++.

58
23/EE/119

Output:

59

You might also like