0% found this document useful (0 votes)
3 views

mineOOPFile.docx (7)

The document outlines a series of C++ programming exercises, including creating classes, function overloading, and implementing a simple banking system. Each exercise includes an aim, theory, algorithm, and code examples demonstrating various programming concepts such as encapsulation, constructors, and different parameter passing mechanisms. The document serves as a practical guide for learning C++ through hands-on coding tasks.

Uploaded by

48 Uma shankar
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)
3 views

mineOOPFile.docx (7)

The document outlines a series of C++ programming exercises, including creating classes, function overloading, and implementing a simple banking system. Each exercise includes an aim, theory, algorithm, and code examples demonstrating various programming concepts such as encapsulation, constructors, and different parameter passing mechanisms. The document serves as a practical guide for learning C++ through hands-on coding tasks.

Uploaded by

48 Uma shankar
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
You are on page 1/ 39

INDEX

S. No. Objective Date Sign

Write a C++ program to print your personaldetails by taking


1
input from the user.

WAP to return the absolute value of variabletypes integer


2
and float using function overloading.

Create a class "employee" that has "Empnumber" and


"Enpname" as data members and member functions
3 getdata() to input data and display() to output data. Writea
main function to create an array of "employee" objects.
Accept and print the details of at least 6 employees.

Write a C++ Program to swap two number byboth call by


4
value and call by reference mechanism.

Write a C++ Program to create a simple banking system in


which the initial balance and the rate of interest are read
5
from the keybound and these values are initialised using
constructors.

Write a program to accept five different numbers by creating


a class called friendfunc1 and friendfunc2 and calculate the
6
average of these numbers by passing objectof the class to
friend function.
WAP that takes students marks and displaysits average
7
using friend functions.

WAP to perform different arithmetic operations using


8
inline functions.

WAP to perform string operations usingoperator overloading


9
in C++.

WAP to demonstrate the use of differentaccess specifiers by


10
means of member functions.

WAP to create a member function and invoke it using "this"


11
pointer.

WAP to explain virtual function and calculatearea of


12
triangle and rectangle respectively.

WAP to explain class template and memberfunction get-


13
max() returns the greatest of 2numbers.

WAP to illustrate 1.Division by zero 2.Array index


14
3.Also use multiple catch blocks

15
WAP to implement function overloading.
EXPERIMENT-1
AIM - Write a C++ program to print your personal details by taking input from the user.

THEORY - A class in C++ serves as a blueprint for creating objects with both data (attributes) and
functions (methods). In the program, the `UserData` class encapsulates personal information.

Access specifiers, such as `private` and `public`, control the visibility of class members. Private members,
like `name` and `age`, are only accessible within the class, while public members can be accessed from
outside.

The `setData` function is a public method used for input, and the `getData` function is used for displaying
the stored data, following the principles of encapsulation, where the internal representation of the class is
hidden from external access, allowing controlled interaction with the object.

ALGORITHM -

1. Start the program.


2. Define a class PersonalDetails with private data members name and age.
3. Define a public member function setData() in the class PersonalDetails:
4. Print "Enter your name: " and read the input from the user into name.
5. Print "Enter your age: " and read the input from the user into age.
6. Define another public member function getData() in the class PersonalDetails:
7. Print "Name: " followed by the value of name.
8. Print "Age: " followed by the value of age.
9. In the main() function, create an object pd of class PersonalDetails.
10. Call the setData() function for object pd to read and store the user’s name and age.
11. Call the getData() function for object pd to print the user’s name and age.
12. End the program.

CODE-

#include <iostream> using namespace std; class personaldata{

int age; string name;


public:

void setdata(){

cout<<"enter your name:"; cin>>name ;

cout<<"enter your age:"; cin>>age;

void getdata(){ cout<<"\nName:"<<name<<"\n"; cout<<"Age:"<<age<<"\n";

};

int main(){

personaldata personaldata; personaldata.setdata(); personaldata.getdata(); return 0;

OUTPUT-

EXPERIMENT – 2
AIM - WAP to return the absolute value of variable types integer and float using function overloading.
THEORY - Function overloading is a feature in C++ that allows multiple functions within the same
scope to have the same name but different parameters. This enables the same function name to be used for
different data types or different numbers of parameters, making code more flexible and readable. In the
program above, we utilized function overloading to create two functions with the same name,
`absoluteValue`, but with different parameter types (int and float). When we call this function, the
compiler determines which version to execute based on the arguments provided, allowing us to calculate the
absolute value for both integer and floating- point numbers using a single, intuitively named function.

ALGORITHM-

1. It defines two overloaded functions named absolute. One takes an integer as an argument, and the
other takes a float as an argument. These functions calculate the absolute value of their respective
input types and return the result.

1. In the main function, two variables are declared: int a with a value of -5 and float b with a value of 5.5.

1. The program then calls the absolute function for both a and b and displays the absolute values using
cout.

1. Finally, the program uses the system("pause") function to pause the console window so that the output
can be viewed before the program exits, and it returns 0 to indicate successful execution.

CODE-

#include <iostream> using namespace std;

int absolute(int); float absolute(float); int main() {

int a = -5; float b = 5.5;

cout<<"Absolute value of "<<a<<" = "<<absolute(a)<<endl; cout<<"Absolute value of "<<b<<" = "


<<absolute(b) <<endl;

system("pause"); return 0;

}
int absolute(int var) { if (var < 0)

var = -var; return var;

float absolute(float var){ if (var < 0.0)

var = -var; return var;

OUTPUT-

EXPERIMENT – 3
AIM - Create a class "employee" that has "Empnumber" and "Enpname" as data members and member
functions getdata() to input data and display() to output data. Writea main function to create an array of
"employee" objects. Accept and print the details of at least 6 employees.

THEORY - In the program, the "Employee" class acts as a prototype for creating objects. Eachobject of
this class contains both data (attributes) and behavior (methods) pertaining to employees. This
encapsulation ensures that the data members (Empnumber and Empname in this case) are bundled with the
methods (getData and display), enhancing data integrity and security.

Objects, which are instances of a class, are used to represent real-world entities. In this program,
"Employee" class objects symbolize individual employees, and their data is manipulated using the defined
member functions. These member functions or methods are unique to the class and facilitate the
encapsulated behavior. In this program, "getData" is employed to input employee data, while "display" is
used to showcase employee details. Overall, the program illustrates how OOP principles like classes,
objects, encapsulation, and methods contribute to a structured and modular approach for managing
employee data, whichcan be extrapolated to various real-world situations.

ALGORITHM-
1. Define a class Employee with private data members Empnumber and Empname.

1. Implement member functions getdata() to input employee data and display() to output employee data.
2. In the main function, create an array of Employee objects to store the details of at least 6
employees.
3. Use a loop to input employee details using the getdata() function.

1. Output the employee details using the display() function.

1. Repeat the process for each employee.

1. Display the details of all employees at the end.

CODE -

#include <iostream> #include <string> class Employee { public:

int Empnumber; std::string Empname;

void getdata() {

std::cout << "Enter Employee Number: "; std::cin >> Empnumber;

std::cin.ignore(); // Clear the newline character from the buffer std::cout << "Enter Employee Name: ";

std::getline(std::cin, Empname);

void display() {

std::cout << "Employee Number: " << Empnumber << std::endl; std::cout << "Employee Name: " <<
Empname << std::endl;

};

int main() {
const int num_employees = 6; Employee employees[num_employees]; for (int i = 0; i < num_employees;
++i) {

employees[i].getdata();

std::cout << "\nEmployee Details:" << std::endl; for (int i = 0; i < num_employees; ++i) {

employees[i].display(); std::cout << std::endl;

return 0;

OUTPUT-

EXPERIMENT – 4
AIM - Write a C++ Program to swap two numbers by both call by value and call by reference
mechanism.
Theory - Call by value and call by reference are two key techniques in programming for transferring
arguments to functions. Call by value entails creating duplicates of the given values, ensuring that
modifications within the function do not impact the original data. On the other hand, call byreference uses
references or pointers to the actual variables, allowing for direct alteration of the original data.
Encapsulation, a central principle in Object-Oriented Programming (OOP), involves grouping data and
associated methods within a class, improving data safety and integrity by regulating access. In
programming, references act as aliases or pointers to variables,permitting direct changes to the underlying
data. These principles, essential in both procedural and OOP, have significant roles in structuring and
manipulating data in software development.

ALGORITHM-

For swapping value:

1. Define a function ‘swapByValue’ that takes two integer parameters, ‘a’ and ‘b’.
2. Inside the function, create a temporary variable ‘temp’ to store the value of ‘a’.
3. Swap the values of ‘a’ and ‘b’ using the temporary variable.
4. The numbers are swapped within the function, but the original values in the ‘main’ function remain
unchanged.

For swapping by reference:

1. Define a function ‘swapByReference’ that takes two integer references, ‘a’ and ‘b’.
2. Inside the function, create a temporary variable ‘temp’ to store the value of ‘a’.
3. Swap the values of ‘a’ and ‘b’ using the temporary variable.
4. The numbers are swapped within the function, and the changes are reflected in the original variables in
the ‘main’ function.

CODE –

#include <iostream>

// Function to swap two numbers using call by value void swapByValue(int a, int b) {

int temp = a; a = b;

b = temp;

std::cout << "Inside swapByValue function: a = " << a << ", b = " << b << std::endl;

}
// Function to swap two numbers using call by reference void swapByReference(int &a, int &b) {

int temp = a; a = b;

b = temp;

std::cout << "Inside swapByReference function: a = " << a << ", b = " << b << std::endl;

int main() {

int num1, num2;

// Input two numbers

std::cout << "Enter the first number: "; std::cin >> num1;

std::cout << "Enter the second number: "; std::cin >> num2;

// Swap by value swapByValue(num1, num2);

std::cout << "After swapByValue function: num1 = " << num1 << ", num2 = " << num2 << std::endl;

// Swap by reference swapByReference(num1, num2);

std::cout << "After swapByReference function: num1 = " << num1 << ", num2 = " << num2 << std::endl;

return 0;

OUTPUT-
EXPERIMENT – 5
AIM- Write a C++ Program to create a simple banking system in which the initial balance and the rate of
interest are read from the keybound and these values are initialised using constructors.

Theory - Constructors are unique member functions in C++ that are automatically triggered when an
object is instantiated. Their purpose is to initialize the data members of the object. In thegiven program, the
BankAccount class possesses a constructor that takes the initial balance and interest rate as parameters.
Upon creation of an object of this class, this constructor is automatically called to initialize the data
members of the object. Constructors play a vital role in guaranteeing that objects are in a valid condition
upon their creation, and they simplify the process of object initialization and configuration.

ALGORITHM-

1. Define a class BankAccount with private member variables: accountHolder, balance, and
interestRate.
2. Create a constructor for the BankAccount class to initialize the account with a name, initial
balance, and interest rate.
3. Implement member functions within the BankAccount class:
deposit: Allows the user to deposit money into the account. Checks if the amount is positive.
withdraw: Allows the user to withdraw money from the account. Checks if the amount is positive
and doesn't exceed the current balance.
calculateInterest: Calculates and adds interest to the account balance based on the given interest
rate.
displayAccount: Displays the account holder's name, current balance, and interest rate.
4. In the main function:
Declare variables name, initialBalance, and rate to store the user's input for the account holder's
name, initial balance, and interest rate.
5. Prompt the user to enter the account holder's name, initial balance, and interest rate using
std::cin.
6. Create a BankAccount object named account using the constructor, passing the user's input as
arguments.
7. Create a menu-driven loop to interact with the bank account:
Display a menu with options for deposit, withdrawal, interest calculation, account details, and
exit.
Prompt the user for their choice.
Use a switch statement to handle each menu option:
For deposit, get the deposit amount from the user and call the deposit method.
For withdrawal, get the withdrawal amount from the user and call the withdraw method.
For interest calculation, call the calculateInterest method.
For displaying account details, call the displayAccount method.
For exit, display a goodbye message and exit the program.
8. Repeat the menu loop until the user chooses to exit (e.g., when choice is 5).

1. End the program with a return statement.

CODE-

#include <iostream> #include <string>

class BankAccount { private:

std::string accountHolder; double balance;

double interestRate;

public:

// Constructor to initialize account with a name, initial balance, and interest rate BankAccount(const
std::string& name, double initialBalance, double rate) {

accountHolder = name; balance = initialBalance; interestRate = rate;

// Function to deposit money into the account void deposit(double amount) {

if (amount > 0) { balance += amount;

std::cout << "Deposited $" << amount << " into the account." << std::endl;

} else {

std::cout << "Invalid deposit amount." << std::endl;

// Function to withdraw money from the account void withdraw(double amount) {


if (amount > 0 && amount <= balance) { balance -= amount;

std::cout << "Withdrawn $" << amount << " from the account." << std::endl;

} else {

std::cout << "Invalid withdrawal amount or insufficient balance." << std::endl;

// Function to calculate interest on the account balance void calculateInterest() {

double interest = balance * (interestRate / 100); balance += interest;

std::cout << "Interest added: $" << interest << std::endl;

// Function to display the account details void displayAccount() {

std::cout << "Account Holder: " << accountHolder << std::endl; std::cout << "Current Balance: $" <<
balance << std::endl; std::cout << "Interest Rate: " << interestRate << "%" << std::endl;

};

int main() { std::string name;

double initialBalance, rate;

std::cout << "Enter the account holder's name: "; std::cin >> name;

std::cout << "Enter the initial balance: "; std::cin >> initialBalance;

std::cout << "Enter the interest rate (%): "; std::cin >> rate;

// Create a BankAccount object using the constructor BankAccount account(name, initialBalance, rate);
int choice; do {

std::cout << "\nBank Account Menu:\n"; std::cout << "1. Deposit\n";

std::cout << "2. Withdraw\n"; std::cout << "3. Calculate Interest\n";

std::cout << "4. Display Account Details\n"; std::cout << "5. Exit\n";

std::cout << "Enter your choice: "; std::cin >> choice;

switch (choice) { case 1:

double depositAmount;

std::cout << "Enter the deposit amount: $"; std::cin >> depositAmount; account.deposit(depositAmount);

break; case 2:

double withdrawAmount;

std::cout << "Enter the withdrawal amount: $"; std::cin >> withdrawAmount;
account.withdraw(withdrawAmount);

break; case 3:

account.calculateInterest(); break;

case 4:

account.displayAccount(); break;

case 5:

std::cout << "Exiting the program. Goodbye!" << std::endl; break;

default:

std::cout << "Invalid choice. Please select a valid option." << std::endl;

} while (choice != 5);

return 0;

}
OUTPUT-

EXPERIMENT – 6
AIM - Write a program to accept five different numbers by creating a class called friendfunc1and
friendfunc2 and calculate the average of these numbers by passing object of the class to friend function.

Theory - In C++, friend functions are unique non-member functions that are designated as friends of a
class, granting them access to the class's private and protected members. In the givenprogram, the function
calculateAverage is declared a friend of the FriendFunc1 class, thereby gaining access to FriendFunc1's
private data members. This is beneficial when a function must interact with multiple classes or when it
requires access to private members for certain operations without breaching encapsulation. Friend
functions are notably useful in promoting cooperation between classes while preserving data security.

ALGORITHM-

1. Define two classes friendfunc1 and friendfunc2.


2. In class friendfunc1, declare an array of integers num to store the five numbers.
3. Define a constructor for class friendfunc1 that accepts five integers as parameters andstores them in
the num array.
4. Declare a friend function calculateAverage in class friendfunc1. This function will bedefined in class
friendfunc2.
5. In class friendfunc2, define the function calculateAverage. This function accepts anobject of class
friendfunc1 as parameter.
6. Inside the calculateAverage function, calculate the sum of the numbers stored in the numarray of the
passed object. Then calculate the average by dividing the sum by 5.
7. In the main function, create an object of class friendfunc1 and initialize it with fivenumbers. Then
create an object of class friendfunc2.
8. Call the calculateAverage function on the object of class friendfunc2, passing the objectof class
friendfunc1 as argument.

CODE-

#include<iostream> using namespace std;

class friendfunc2; // Forward declaration class friendfunc1 {

public:

int num[5];

friendfunc1(int a, int b, int c, int d, int e) { num[0] = a; num[1] = b;

num[2] = c;

num[3] = d;

num[4] = e;

friend void calculateAverage(friendfunc2, friendfunc1); // Friend function

};

class friendfunc2 { public:

void calculateAverage(friendfunc1 obj) { double sum = 0; for(int i=0; i<5; i++) { sum += obj.num[i];

cout << "Average: " << sum/5 << endl;


}

};

int main() {

float n1, n2, n3, n4, n5;

cout << "Enter five numbers: ";

cin >> n1 >> n2 >> n3 >> n4 >> n5; friendfunc1 obj1(n1, n2, n3, n4, n5); friendfunc2 obj2;
obj2.calculateAverage(obj1);

return 0;

OUTPUT-

EXPERIMENT – 7
AIM- WAP that takes students marks and displays its average using friend functions.

THEORY- A friend function is a function that is not a member of a class but is granted access toits
private and protected members. In the program, calculateAverage is a friend function that canaccess the
private Marks data members of Student class, allowing it to calculate the average of the students' marks.
ALGORITHM-
1. Create a class Student to store the student's name and marks in three subjects (Math, English,and
Science) as private data members.

1. Create a constructor for the Student class to initialize the name and marks.

1. Define a displayInfo member function to display the student's name and marks.

1. Declare a friend function calculateAverage in the Student class to calculate the average of
thestudent's marks.

1. Define the calculateAverage friend function outside the class, which calculates the average ofthe
three subjects' marks.

1. In the main function, create a Student object with a name and marks, display the
student'sinformation, and calculate and display the average marks using the friend function.

CODE-

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

class Student { private:

string name; int math; int english; int science;

public:

Student(std::string n, int m, int e, int s) : name(n), math(m), english(e), science(s) {}

void displayInfo() {

cout << "Student Name: " << name << endl;


cout << "Math Marks: " << math << endl; cout << "English Marks: " << english << endl; cout <<
"Science Marks: " << science << endl;

friend float calculateAverage(Student s);

};

// Friend function to calculate average float calculateAverage(Student s)

return (s.math + s.english + s.science) / 3.0;

int main() {

Student student("SAMARTH", 70, 95, 68);

student.displayInfo();

cout << "Average Marks: " << calculateAverage(student) << endl;

return 0;

}
OUTPUT-

EXPERIMENT – 8
AIM- WAP to perform different arithmetic operations using inline functions.

THEORY- Inline functions in C++ serve as a method to enhance the efficiency of a program by
circumventing the additional load of a standard function call. When a function is marked as inline, the C++
compiler embeds the function's code directly at the location of the call, rather than establishing a distinct
function call stack. This minimizes the overhead associated with function calls and can lead to quicker
execution of the program.

Inline functions are generally employed for small functions that are invoked frequently, where the
overhead of function calls is substantial. They are declared using the inline keyword preceding the
function definition. It's crucial to understand that the application of inline functions is merely a
recommendation to the compiler, and it's ultimately the compiler's decision to complywith the inlining
request. Nonetheless, they can be extremely advantageous in scenarios where performance optimization is
paramount.

ALGORITHM-

1. Create inline functions for each arithmetic operation (addition, subtraction, multiplication, and
division) to perform the respective operations.
2. In the 'main' function, declare variables 'num1', 'num2', and 'operation' to store the two numbers and
the desired arithmetic operation character.
3. Prompt the user to enter two numbers and the arithmetic operation.
4. Use a 'switch' statement to determine which arithmetic operation to perform based on the
'operation' character entered by the user.
5. Call the corresponding inline function and store the result in the 'result' variable.
6. If the user enters an invalid operation, display an error message.
7. Display the result to the user.

CODE-

#include <iostream>
// Inline function for addition

inline double add(double a, double b) { return a + b;

// Inline function for subtraction

inline double subtract(double a, double b) { return a - b;

// Inline function for multiplication

inline double multiply(double a, double b) { return a * b;

// Inline function for division

inline double divide(double a, double b) { if (b == 0) {

std::cerr << "Error: Division by zero!" << std::endl; return 0;

return a / b;

int main() {

double num1, num2; char operation;

std::cout << "Enter two numbers: "; std::cin >> num1 >> num2;

std::cout << "Enter the arithmetic operation (+, -, *, /): "; std::cin >> operation;

double result; switch (operation) {

case '+':

result = add(num1, num2); break;


case '-':

result = subtract(num1, num2); break;

case '*':

result = multiply(num1, num2); break;

case '/':

result = divide(num1, num2); break;

default:

std::cerr << "Invalid operation" << std::endl; return 1;

std::cout << "Result: " << result << std::endl;

return 0;

OUTPUT-

EXPERIMENT – 9
AIM- WAP to perform string operations using operator overloading in C++.

THEORY- Operator overloading in C++ is a powerful feature that allows you to redefine how operators
work with user-defined types or objects. This provides a special meaning to an operatorwhen it is used with a
user-defined data type.
When an operator is overloaded, the compiler includes the function's code directly at the call site, instead of
creating a separate function call stack. This reduces the function call overhead and canresult in faster
program execution.

In C++, most operators can be overloaded. For an operator to be overloaded, at least one of theoperands
must be a user-defined object. This makes C++ a versatile language for custom data structures and classes.

However, it's important to note that not all C++ operators can be overloaded. Also, the use ofoperator
overloading should be done judiciously as it can lead to code that is difficult to understand and maintain if
not used properly.

In summary, operator overloading enhances the expressiveness of the language, allowing

user-defined types to behave in ways that are intuitive and easy to understand. It's a key featurethat
contributes to the power and flexibility of C++.

ALGORITHM-

1. Create a 'String' class to represent strings with a 'char*' data member to store the string.
2. Overload the '+' operator to perform string concatenation. Inside the operator overloading function,
allocate memory for the result string, copy the contents0 of the two strings, and return a new 'String'
object.
3. Overload the '==' operator to compare two 'String' objects by using the 'strcmp' function.
4. Overload the '<<' operator as a friend function to enable easy output of 'String' objects.
5. In the 'main' function, create 'String' objects and demonstrate string concatenation and comparison
using operator overloading.

CODE-

#include <iostream> #include <cstring>

class String { private:

char* str; public:

// Constructor

String(const char* s = nullptr) { if (s) {

str = new char[strlen(s) + 1]; strcpy(str, s);

} else {

str = nullptr;

}
// Destructor

~String() { if (str) {

delete[] str;

// Overload the + operator for string concatenation String operator+(const String& other) const {

char* result = new char[strlen(str) + strlen(other.str) + 1]; strcpy(result, str);

strcat(result, other.str); return String(result);

// Overload the == operator for string comparison bool operator==(const String& other) const {

return strcmp(str, other.str) == 0;

// Overload the << operator for output

friend std::ostream& operator<<(std::ostream& os, const String& s) { os << s.str;

return os;

};

int main() {

String s1("Hello, ");

String s2("world!");

String s3 = s1 + s2; // Concatenation using operator overloading std::cout << "s1 + s2 = " << s3 <<
std::endl;
String s4("Hello, world!");

if (s3 == s4) { // Comparison using operator overloading std::cout << "s3 and s4 are equal." << std::endl;

} else {

std::cout << "s3 and s4 are not equal." << std::endl;

return 0;

Output-

EXPERIMENT – 10
AIM- WAP to demonstrate the use of different access specifiers by means of member functions.
THEORY- In C++, access specifiers are utilized to dictate the visibility and reachability of elements
within a class. C++ has three types of access specifiers:

Public: If class members are marked as public, they can be accessed from any location in the
program without any restrictions.
Private: Class members labeled as private cannot be accessed from outside the class. These
members are designed to conceal the class's internal workings.
Protected: Protected class members are akin to private ones, but they can be accessed by
subclasses (derived classes).
Access specifiers play a crucial role in enforcing encapsulation and managing interactions withclass
members. Public members offer a public interface, private members conceal implementation specifics, and
protected members grant access related to inheritance. This is a key principle in object-oriented
programming and is vital for producing well-organized and maintainable code.

ALGORITHM-

1. Start

1. Include the necessary header files, especially iostream.

1. Define a class AS.

1. Inside the class, declare a public integer variable publicVar, a private integer variable privateVar,
and a protected integer variable protectedVar.

1. Create a constructor for the class, initializing all the variables with different values.

1. Define a public member function display() to display the values of all three variables.

1. In the main function:

Create an object of the A class.

Access the public variable directly and display its value.

Call the display() member function to display the values of all three variables.
CODE-

Attempt to access the private and protected variables directly (commented out), whichwould result
in compilation errors.

#include <iostream> using namespace std; class AS{ public:

int publicVar;

AS() {

publicVar = 50;

privateVar = 60;

protectedVar = 40;

void display() {

cout << "Public Variable (publicVar): " << publicVar << endl; cout << "Private Variable (privateVar): " <<
privateVar << endl;

cout << "Protected Variable (protectedVar): " << protectedVar << endl;

private:

int privateVar;

protected:

int protectedVar;

};

int main() { AS obj;


cout << "Accessing public variable from main: " << obj.publicVar << endl; obj.display();

// Accessing private and protected variables directly would result in compilation errors.

// Uncommenting the following lines will demonstrate those errors.

// cout << "Accessing private variable from main: " << obj.privateVar << endl;

// cout << "Accessing protected variable from main: " << obj.protectedVar << endl;

return 0;

OUTPUT-

EXPERIMENT-11
AIM- WAP to create a member function and invoke it using "this" pointer.

THEORY- Pointers are a type of variable that hold the memory address of another variable. They are a
key aspect of C++ and serve various functions, such as dynamic memory allocationand variable
manipulation.

The "this" pointer in C++ is a unique pointer that refers to the current class object. It is implicitlypresent in
all non-static member functions of a class. The "this" pointer is utilized to access the members (variables
and functions) of the current object. It becomes particularly useful when there is ambiguity between class
member variables and function parameters with identical names. By employing "this," it becomes evident
that the reference is to the class member.
ALGORITHM-

1. Define a class 'MyClass' with the following member functions:


'printAddress': Prints the address of the current instance (using the "this" pointer).
'printValues': Prints the address of the current instance and two integer values passed as
parameters.
2. In the 'main' function:
Create two instances of the 'MyClass' class, 'obj1' and 'obj2'.
3. Call the 'printAddress' function for both 'obj1' and 'obj2' instances, which prints the address of each
instance using the "this" pointer.
4. Declare two integer variables, 'x' and 'y', and initialize them with values (x = 10, y = 20).
5. Call the 'printValues' function on 'obj1', passing the values of 'x' and 'y' as parameters. This
function prints the address of 'obj1' and the values of 'x' and 'y'.
6. Call the 'printValues' function on 'obj2', passing different values (x = 30, y = 40) as parameters. This
function prints the address of 'obj2' and the new values of 'x' and 'y'.
7. The program ends.

CODE-

#include <iostream>

class MyClass { public:

void printAddress() {

std::cout << "Address of this instance: " << this << std::endl;

void printValues(int a, int b) {

std::cout << "Address of this instance: " << this << std::endl; std::cout << "a: " << a << ", b: " << b <<
std::endl;

};

int main() { MyClass obj1; MyClass obj2;

obj1.printAddress(); obj2.printAddress();
int x = 10, y = 20; obj1.printValues(x, y); obj2.printValues(30, 40);

return 0;

OUTPUT-

EXPERIMENT – 12
AIM- WAP to explain virtual function and calculate area of triangle and rectangle respectively.
THEORY- Virtual functions are a crucial aspect of object-oriented programming in C++. Theyenable a
function in a base class to be superseded by a function in a subclass. If a function is marked as virtual

in the base class, it can be redefined in the subclasses. This becomes particularly beneficial when dealing
with a class hierarchy and there's a need to offer varying implementations of the same function depending on
the subclass.

ALGORITHM-

1. We define a base class 'Shape' with a virtual function 'area ()'.


2. We create two derived classes 'Triangle' and 'Rectangle', each with its own implementation of the 'area
()' function.
3. In the 'main' function, we create an array of pointers to 'Shape' objects and initialize them with
instances of 'Triangle' and 'Rectangle'.
4. We use a loop to calculate and display the areas of the shapes, taking advantage of polymorphism to
call the correct 'area ()' function for each shape.
5. Finally, we clean up the dynamically allocated objects to avoid memory leaks.

CODE-
#include <iostream>

class Shape { public:

virtual double area() { return 0.0;

};

class Triangle : public Shape { private:

double base; double height;

public:

Triangle(double b, double h) : base(b), height(h) {}

double area() override { return 0.5 * base * height;

};

class Rectangle : public Shape { private:

double length; double width;

public:

Rectangle(double l, double w) : length(l), width(w) {}

double area() override { return length * width;

};

int main() {
Shape* shapes[2];

shapes[0] = new Triangle(5.0, 8.0); shapes[1] = new Rectangle(4.0, 6.0);

for (int i = 0; i < 2; i++) {

std::cout << "Area of shape " << i + 1 << ": " << shapes[i]->area() << std::endl;

// Clean up the dynamically allocated objects for (int i = 0; i < 2; i++) {

delete shapes[i];

return 0;

OUTPUT-

EXPERIMENT – 13

AIM- WAP to explain class template and member function get-max() returns the greatest of 2
numbers.

THEORY- Class templates in C++ are a feature of generic programming, which allows for code
reusability and the handling of multiple data types with a single class or function.
A class template is defined using the template keyword followed by template parameters enclosed in <

>. The template parameters can represent any type, and they are specified when anobject of the template
class is created.

Class templates provide flexibility and efficiency as they enable classes to work with multipledata types
while maintaining type safety. This reduces code duplication and improves code maintenance and
readability.

ALGORITHM-

1. We define a class template 'MaxFinder' with a single type parameter 'T'. This class has a
constructor that takes two values of type 'T' and a 'get_max()' member function that returns the
maximum of the two values.

1. In the 'main()' function, we create instances of 'MaxFinder' for different data types (int, double,
and char).

1. We call the 'get_max()' function on each instance to find and display the maximum values.

CODE-

#include <iostream>

// Class template for finding the maximum of two values template <typename T>

class MaxFinder { public:

MaxFinder(T a, T b) : value1(a), value2(b) {}

T get_max() {

return (value1 > value2) ? value1 : value2;

}
private:

T value1; T value2;

};

int main() {

// Create instances of MaxFinder with different data types MaxFinder<int> intMax(10, 20);

MaxFinder<double> doubleMax(3.14, 2.71); MaxFinder<char> charMax('A', 'Z');

// Find the maximum values and display them

std::cout << "Maximum integer value: " << intMax.get_max() << std::endl; std::cout << "Maximum
double value: " << doubleMax.get_max() << std::endl; std::cout << "Maximum character value: " <<
charMax.get_max() << std::endl;

return 0;

OUTPUT-

EXPERIMENT – 14

AIM- WAP to illustrate


1. Division by zero
2. Array index
3. Also use multiple catch blocks

THEORY-

Divide by Zero: In mathematics, division by zero is undefined because it leads to results that are
contradictory or nonsensical. In C++, if you try to divide a number by zero, it will either cause a runtime
error or produce an undefined result. This is because the operation cannot be performed in a meaningful
way.

Array Index: In C++, arrays are zero-indexed, meaning that the first element of the array is at index 0, the
second element is at index 1, and so on. If you try to access an array element using an index that is out of
bounds (either negative or greater than or equal to the size of the array), itwill lead to undefined behavior,
which could include accessing random memory locations or causing a runtime error.

Catch Blocks: In C++, exceptions are used to handle errors and other exceptional events that occur during
the execution of a program. When an error occurs, an exception can be “thrown” using the throw
keyword. This exception must then be “caught” using a catch block. The catchblock contains code that
handles the exception and decides what action should be taken. If an exception is thrown but not caught
(i.e., there is no suitable catch block), the program will terminate.

ALGORITHM-

1. Start the program.


2. Initialize an array arr of size 5 with values {1, 2, 3, 4, 5}.
3. Set index to 6 (an out-of-bounds index for the array) and divisor to 0 (which will causedivision by
zero).
4. Begin the first try block:
5. If index is less than 0 or greater than or equal to 5 (the size of the array), throw anexception with
the message “Index out of bounds!”.
6. If no exception is thrown, print the array element at the given index.
7. Begin the first catch block:
8. Catch the exception and print the error message.
9. Begin the second try block:
10. If divisor is zero, throw an exception with the message “Division by zero!”.
11. If no exception is thrown, print the result of dividing 10 by divisor.
12. Begin the second catch block:
13. Catch the exception and print the error message.
14. End the program.

CODE-

#include<iostream> using namespace std;


int main() {

int arr[5] = {1, 2, 3, 4, 5};

int index = 6; // Out-of-bounds index int divisor = 0; // Zero divisor

try {

if(index < 0 || index >= 5) { throw "Index out of bounds!";

cout << "Array element: " << arr[index] << endl;

catch(const char* msg) { cerr << msg << endl;

try {

if(divisor == 0) {

throw "Division by zero!";

cout << "Division result: " << 10 / divisor << endl;

catch(const char* msg) { cerr << msg << endl;

return 0;

OUTPUT-
EXPERIMENT – 15

AIM- WAP to implement function overloading.

THEORY- Function overloading is a feature in C++ where two or more functions can have the same
name but different parameters. It allows programmers to write functions to do conceptuallythe same thing
on different types of data without changing the function name.

Different Parameters: Overloaded functions must differ in the number and/or type of theirparameters.
They can’t differ only by the return type.

Compile-Time Polymorphism: Function overloading is a way to achieve compile-time polymorphism


where the appropriate function is determined during compile time.

Same Scope: All overloaded functions must exist in the same scope.

Automatic Type Conversion: If a function call doesn’t match any defined function but canmatch after type
conversion, C++ will apply the necessary conversions.

ALGORITHM-

1. Define multiple functions with the same name but different parameter lists.
2. When you call the overloaded function, the compiler selects the appropriate function to call based on
the argument types you provide.

CODE-

#include <iostream>

// Function to add two integers int add(int a, int b) {

return a + b;
}

// Function to add two double values double add(double a, double b) {

return a + b;

int main() {

int intResult;

double doubleResult;

intResult = add(5, 7);// Calls the first function (int version) doubleResult = add(3.5, 2.2);// Calls the second
function (double version) std::cout << "Sum of integers: " << intResult << std::endl;

std::cout << "Sum of doubles: " << doubleResult << std::endl; return 0;

OUTPUT-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy