0% found this document useful (0 votes)
6 views22 pages

C++ Class Programming Examples

The document contains multiple programming exercises demonstrating various concepts in C++, including friend functions, operator overloading, class templates, and file handling. Each practical exercise includes an aim, code implementation, and explanation of the functionality. The exercises cover topics such as finding the greatest of two numbers, string manipulation, stack and queue implementations, and removing whitespace from files.
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)
6 views22 pages

C++ Class Programming Examples

The document contains multiple programming exercises demonstrating various concepts in C++, including friend functions, operator overloading, class templates, and file handling. Each practical exercise includes an aim, code implementation, and explanation of the functionality. The exercises cover topics such as finding the greatest of two numbers, string manipulation, stack and queue implementations, and removing whitespace from files.
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

​Practical No-3​

​AIM:-​​Write a program to find the greatest of two given numbers in two​


​different classes using friend function​

​Code:-​
​include​​
# <iostream>​
using​​
​ namespace​​std;​
class​​
​ B;​
class​​
​ A {​
int num1;​

public​
​ :​

void setData(int n) {​

num1 = n;​

}​

friend​​
​ void findGreatest(A, B);​
};​

class​​
​ B {​
int num2;​

public​
​ :​

void setData(int n) {​

num2 = n;​

}​

friend​​
​ void findGreatest(A, B);​
};​

void findGreatest(A objA, B objB) {​



if​​
​ (objA.num1 > objB.num2)​
cout << "The greatest number is: " << objA.num1 << endl;​

else​​
​ if​​
(objB.num2 > objA.num1)​
cout << "The greatest number is: " << objB.num2 << endl;​

else​

cout << "Both numbers are equal." << endl;​

}​

int main() {​

A a;​

B b;​

int x, y;​

​out << "Enter first number: ";​
c
cin >> x;​

}​

​OUTPUT:-​
​Practical No-4.​
​AIM:-​​Implement a class string containing the following functions:​
+​​operator to carry out the concatenation of strings.​
​a. Overload​​

=​​operator to carry out string copy.​


​b. Overload​​

<=​​operator to carry out the comparison of strings.​


​c. Overload​​

​d. Function to display the length of a string.​

tolower( )​​to convert upper case letters to lower case.​


​e. Function​​

toupper( )​​to convert lower case letters to upper case.​


​f. Function​​

​CODE:-​
​ include <iostream>​
#
​#include <cstring>​
​using namespace std;​

​class String {​
​char str[100];​
​public:​
​String() {​
​str[0] = '\0';​
​}​
​String(const char s[]) {​
​strcpy(str, s);​
​}​
​void display() const {​
​cout << str << endl;​
​}​
​void length() const {​
​cout << "Length of string: " << strlen(str) << endl;​
​}​
​void toLower() {​
​for (int i = 0; str[i] != '\0'; i++) {​
​if (str[i] >= 'A' && str[i] <= 'Z')​
​str[i] = str[i] + 32;​
​}​
​}​
​void toUpper() {​
​for (int i = 0; str[i] != '\0'; i++) {​
​if (str[i] >= 'a' && str[i] <= 'z')​
​str[i] = str[i] - 32;​
​}​
​}​
​String operator+(const String &s) {​
​String temp;​
​strcpy([Link], str);​
​strcat([Link], [Link]);​
​return temp;​
​}​
​String operator=(const String &s) {​
​strcpy(str, [Link]);​
​return *this;​
​}​
​bool operator<=(const String &s) {​
​if (strcmp(str, [Link]) <= 0)​
​return true;​
​else​
​return false;​
​}​
​};​

​int main() {​
​String s1("Hello");​
​String s2("World");​
​String s3;​

c​ out << "Initial strings:" << endl;​


​cout << "s1 = "; [Link]();​
​cout << "s2 = "; [Link]();​

​s3 = s1 + s2;​
c​ out << "\nAfter concatenation (s1 + s2): ";​
​[Link]();​

s​ 1 = s2;​
​cout << "\nAfter assignment (s1 = s2): ";​
​[Link]();​

​if (s1 <= s2)​


​cout << "\ns1 is less than or equal to s2." << endl;​
​else​
​cout << "\ns1 is greater than s2." << endl;​

​cout << "\n"; [Link]();​

c​ out << "\nConverting s3 to lowercase: ";​


​[Link]();​
​[Link]();​
​cout << "Converting s3 to uppercase: ";​
​[Link]();​
​[Link]();​

​return 0;​
​}​

​Explanation:​
operator+​​| Concatenates two strings | |​
​| Function | Purpose | | :---: | :---: | |​​
operator=​​| Copies one string to another | |​​
​ operator<=​​| Compares two strings​
length()​​| Displays length of​​string | |​​
​lexicographically | |​​ toLower()​​| Converts all​
toUpper()​​| Converts all characters to uppercase |​
​characters to lowercase | |​​
​OUTPUT:-​
​Practical No-5​
​AIM:-​​Create a class called​​LIST​​with two pure virtual​​function​​store()​​and​
retrieve()​
​ ​. To store a value call store and to retrieve​​call retrieve function. Derive​
stack​​and​​
​two classes​​ queue​​from it and override​​
store​​and​​
retrieve​
​.​

​Solution:-​​The solution demonstrates the use of abstract​​classes, pure virtual​


LIST​​base class,​​from which​​
f​unctions, and inheritance to create a​​ STACK​​and​​
QUEUE​
​are derived​

​Code:-​
​#include <iostream>​

​using namespace std;​

​class LIST {​

​public:​

​virtual void store(int value) = 0;​

​virtual int retrieve() = 0;​

​};​

​class STACK : public LIST {​

​int arr[10];​

​int top;​

​public:​

​STACK() { top = -1; }​

​void store(int value) override {​

​if (top == 9)​

​cout << "Stack Overflow!" << endl;​


​else​

​arr[++top] = value;​

​}​

​int retrieve() override {​

​if (top == -1) {​

​cout << "Stack Underflow!" << endl;​

​return -1;​

​} else​

​return arr[top--];​

​}​

​};​

​class QUEUE : public LIST {​

​int arr[10];​

​int front, rear;​

​public:​

​QUEUE() {​

​front = 0;​

​rear = -1;​

​}​

​void store(int value) override {​

​if (rear == 9)​

​cout << "Queue Overflow!" << endl;​

​else​
​arr[++rear] = value;​

​}​

​int retrieve() override {​

​if (front > rear) {​

​cout << "Queue Underflow!" << endl;​

​return -1;​

​} else​

​return arr[front++];​

​}​

​};​

​int main() {​

​LIST* list;​

​cout << "Using Stack:\n";​

​STACK s;​

​list = &s;​

​list->store(10);​

​list->store(20);​

​list->store(30);​

​cout << "Retrieve: " << list->retrieve() << endl;​

​cout << "Retrieve: " << list->retrieve() << endl;​

​cout << "\nUsing Queue:\n";​

​QUEUE q;​

​list = &q;​
​list->store(100);​

​list->store(200);​

​list->store(300);​

​cout << "Retrieve: " << list->retrieve() << endl;​

​cout << "Retrieve: " << list->retrieve() << endl;​

​return 0;​

​}​

​Explanation:​
​●​ ​
LIST​​is an abstract base class (cannot be instantiated)​​because it has​
virtual void store(int) =​​
​pure virtual functions:​​ 0;​​and​​
virtual​
int retrieve() = 0;​
​ ​.​
​●​ ​
STACK​​and​​
QUEUE​​both override these functions.​
​○​ ​
STACK​​→ Implements LIFO (Last In, First Out).​
​○​ ​
QUEUE​​→ Implements FIFO (First In, First Out).​
​ base class pointer (​​
​●​ A LIST*​ store()​​and​​
​) is used to call​​ retrieve()​
​dynamically (runtime polymorphism).​

​OUTPUT:-​
​Practical No-6​
​AIM:-​ ​Write a program to define the function template​​for calculating the​
​square of given numbers with different data types.​

​Code :-​
​ include <iostream>​
#
​using namespace std;​

t​emplate <typename T>​


​T square(T num) {​
​return num * num;​
​}​

​int main() {​
​int intNum = 5;​
​double doubleNum = 3.5;​
​float floatNum = 2.3f;​

c​ out << "Square of integer " << intNum << " is: " << square(intNum) <<​
​endl;​
​cout << "Square of double " << doubleNum << " is: " <<​
​square(doubleNum) << endl;​
​cout << "Square of float " << floatNum << " is: " << square(floatNum) <<​
​endl;​

​return 0;​
​}​
​Output:-​
​Practical No-7​
​AIM:-​​Write a program to demonstrate the use of special functions,​
c​ onstructor and destructor in the class template. The program is used to​
​find the bigger of two entered numbers.​

​Code:-​
​ include <iostream>​
#
​using namespace std;​

t​emplate <class T>​


​class Compare {​
​T num1, num2;​
​public:​
​Compare(T n1, T n2) {​
​num1 = n1;​
​num2 = n2;​
​cout << "Constructor called!" << endl;​
​}​

​void findBigger() {​
​if (num1 > num2)​
​cout << num1 << " is bigger." << endl;​
​else if (num2 > num1)​
​cout << num2 << " is bigger." << endl;​
​else​
​cout << "Both numbers are equal." << endl;​
​}​

​~Compare() {​
​cout << "Destructor called!" << endl;​
​}​
​};​
​int main() {​
​cout << "Comparing integers:" << endl;​
​Compare<int> c1(10, 20);​
​[Link]();​

c​ out << "\nComparing doubles:" << endl;​


​Compare<double> c2(5.5, 3.3);​
​[Link]();​

​return 0;​
​}​

​Output:-​
​Practical No-8​
​AIM:-​​Write a program to perform the deletion of white​​spaces such as​
​ orizontal tab, vertical tab, space, line feed, new line and carriage return​
h
​from a text file and store the contents of the file without the white spaces on​
​another file.​

​Code:-​
​ include <iostream>​
#
​#include <fstream>​
​using namespace std;​

​int main() {​
​char ch;​
​ifstream fin("[Link]");​
​ofstream fout("[Link]");​

​if (!fin) {​
​cout << "Error: Cannot open input file!" << endl;​
​return 1;​
​}​
​if (!fout) {​
​cout << "Error: Cannot create output file!" << endl;​
​return 1;​
​}​

​while ([Link](ch)) {​
​if (ch != ' ' && ch != '\t' && ch != '\v' && ch != '\n' && ch != '\r' && ch !=​
​'\f') {​
​[Link](ch);​
​}​
​}​
​cout << "White spaces removed successfully! Check [Link]" << endl;​

f​[Link]();​
​[Link]();​

​return 0;​
​}​

​Explanation:​
​●​ ​
ifstream​​→ Used to read from the input file (​​
[Link]​
​).​
​​ o
● ​fstream​​→ Used to write to the output file (​​
[Link]​ ​).​
​●​ ​The program reads each character one by one.​
​●​ ​If the character is not a whitespace (​​
' '​ '\t'​
​,​​ '\v'​
​,​​ '\n'​
​,​​ '\r'​
​,​​ ​,​
​\f'​
' ​), it writes it to the new file.​
​ ​ ​At the end, the cleaned text (without spaces or newlines) is stored in​

[Link]​
​ ​.​

​Example Input/Output:​
​●​ ​[Link]:​
​Hello World This is a test.​

​●​ ​[Link]​
​Practical No-9​
​AIM:-​​Write a program to read the class object of student​​info such as​
​ ame, age, sex, height and weight from the keyboard and to store them on​
n
read()​​and​​
​a specified file using​​ write()​​functions.​​Again the same file​
​is opened for reading and displaying the contents of the file on the screen.​

​Solution:-​​The program is designed to:​


​1.​ ​take student information (name, age, sex, height, weight) from the​
​keyboard,​
write()​
​2.​ ​store it in a binary file using​​ ​,​
read()​​to display on the​​screen.​
​3.​ ​and then read it back using​​

​Code:-​
​ include <iostream>​
#
​#include <fstream>​
​#include <cstring>​
​using namespace std;​

​class Student {​
​char name[30];​
​int age;​
​char sex;​
​float height;​
​float weight;​
​public:​
​void getData() {​
​cout << "Enter Name: ";​
​[Link]();​
​[Link](name, 30);​
​cout << "Enter Age: ";​
​cin >> age;​
c​ out << "Enter Sex (M/F): ";​
​cin >> sex;​
​cout << "Enter Height (in cm): ";​
​cin >> height;​
​cout << "Enter Weight (in kg): ";​
​cin >> weight;​
​}​

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

​int main() {​
​Student s;​
​fstream file;​

c​ out << "Enter student information:\n";​


​[Link]();​

​[Link]("[Link]", ios::out | ios::binary);​

​if (!file) {​
​cout << "Error creating file!" << endl;​
​return 1;​
​}​

f​[Link](reinterpret_cast<char*>(&s), sizeof(s));​
​[Link]();​

​cout << "\nData written to file successfully.\n";​


​[Link]("[Link]", ios::in | ios::binary);​

​if (!file) {​
​cout << "Error opening file for reading!" << endl;​
​return 1;​
​}​

​[Link](reinterpret_cast<char*>(&s), sizeof(s));​

c​ out << "\nStudent information read from file:\n";​


​[Link]();​

f​[Link]();​
​return 0;​
​}​

​Explanation:​
​●​ T ​ he class​​ Student​​contains data members: name, age,​​sex, height,​
​weight.​
​●​ ​The program uses​​ write()​​to write the binary data​​of the object into​
​the file.​
​●​ ​It uses​​ read()​​to read the object back from the file.​
​ he file is opened in binary mode (​​
​●​ T ios::binary​
​) to​​avoid text​
​formatting issues.​
​Output:​
​Practical No-10​
​AIM:-​​Write a program to raise an exception if any attempt is made to refer​
​to an element whose index is beyond the array size.​

​Solution:-​​This solution demonstrates how to raise an exception when​


try​
​trying to access an array element beyond its size using​​ ​–​
c
​ atch​​blocks​
throw​​statements.​
​and​​

​Code:-​
​ include <iostream>​
#
​using namespace std;​

​int main() {​
​const int size = 5;​
​int arr[size] = {10, 20, 30, 40, 50};​
​int index;​

c​ out << "Array elements: ";​


​for (int i = 0; i < size; i++) {​
​cout << arr[i] << " ";​
​}​

c​ out << "\n\nEnter the index of element you want to access (0–4): ";​
​cin >> index;​

​try {​
i​f (index < 0 || index >= size) {​
​throw "Array index out of range!"; // throw exception​
​}​

​cout << "Element at index " << index << " = " << arr[index] << endl;​
}​ ​
​catch (const char* msg) {​
​cout << "Exception caught: " << msg << endl;​
​}​
​cout << "Program continues normally after exception handling." << endl;​

​return 0;​
​}​

​Explanation:​
​●​ ​
throw​​→ Used to raise an exception when the index is invalid.​
​●​ ​
try​​block → Contains code that might cause an exception.​
​​ c
● ​atch​​block → Handles the exception and prints an error message.​
​●​ ​The program continues smoothly even after the error is caught.​

​Output 1 (Valid Input):​

​Output 2 (Invalid Input):​

You might also like