[go: up one dir, main page]

0% found this document useful (0 votes)
47 views63 pages

ANURAG CPP Lab Manual A1to10

This C++ program creates a Book class with private data members for the name and price of a book. It defines default, parameterized, and copy constructors to initialize Book objects and display their values. The main function demonstrates creating Book objects using these different constructor types and displaying the initialized name and price values.

Uploaded by

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

ANURAG CPP Lab Manual A1to10

This C++ program creates a Book class with private data members for the name and price of a book. It defines default, parameterized, and copy constructors to initialize Book objects and display their values. The main function demonstrates creating Book objects using these different constructor types and displaying the initialized name and price values.

Uploaded by

andy paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

ASSIGNMENT 1

AIM : WAP in C++ to create a class called as student. Data members are rollno,
name & fees of the student. Write appropriate get () & put () functions to scan
and display the student data.

Theoretical Explanation:

This C++ program demonstrates the creation of a `student` class and the
implementation of two member functions, `get` and `put`, to input and display
student data, respectively. Here's how the program works:

`student` Class : A class named `student` is defined with three private data
members: `rollno` (integer), `name` (string), and `fees` (floating-point number).
These data members represent the roll number, name, and fees of a student.

`get` Member Function : The `get` function is a public member of the `student`
class. It is responsible for collecting input data for a student object. It displays
prompts for the user to input the roll number, name, and fees. The entered
values are then stored in the corresponding data members of the class.

`put` Member Function : The `put` function is another public member of the
`student` class. It is used to display the student's data. It displays the roll
number, name, and fees of the student on the console.

`main` Function : In the `main` function, an instance of the `student` class


called `ans` is created. The program displays a message prompting the user to
enter student details. The `get` function is called to collect these details, and
then, the program displays the student's details using the `put` function.

Return Value: The program returns 0 at the end to indicate successful


execution.

This program showcases the use of object-oriented principles in C++ to


encapsulate data (student details) within a class and provides methods to
interact with the data. By using this class, you can easily create and manage
student records, making the code more organized and maintainable.

Conclusion : This program illustrates the principles of object-oriented


programming in C++. By encapsulating student data within a class, it promotes
data encapsulation, making it easier to maintain and extend the code. This
structure is beneficial for managing and presenting information for various
student records and serves as a foundation for more complex student
management systems.
Algorithm:

1. Start

2. Create a `student` class with private data members:

- `rollno` (integer)

- `name` (string)

- `fees` (floating-point number)

3. Define a public member function `get` within the class:

- Display "Enter Roll Number:" and read the value into `rollno`.

- Display "Enter Name:" and read the value into `name`.

- Display "Enter Fees:" and read the value into `fees`.

4. Define another public member function `put` within the class:

- Display "Student Roll Number:" followed by the value of `rollno`.

- Display "Student Name:" followed by the value of `name`.

- Display "Student Fees:" followed by the value of `fees`.

5. In the `main` function:

- Create an instance of the `student` class called `ans`.

- Display "Enter Student Details:"

- Call the `get` function to input student data (roll number, name, and fees).

- Display "Student Details:"

- Call the `put` function to display the entered student data.

6. Return 0 to indicate successful program execution.

7. End

Source Code:
#include<iostream>

#include<string>

using namespace std;

class student {

private: int rollno;

string name;

float fees;

public: void get() {

cout << "Enter Roll Number : ";

cin >> rollno;

cout << "Enter Name : ";

cin >> name;

cout << "Enter Fees : ";

cin >> fees;

void put() {
cout << "Student Roll Number : " << rollno << endl;

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

cout << "Student Fees : " << fees << endl;

};

int main() {

student ans;

cout << "Enter Student Details : " << endl;

cout << endl;

ans.get();

cout << endl;

cout << "Student Details : " << endl;

cout << endl;

ans.put();

return 0;

Output :
ASSIGNMENT 2
AIM: WAP in C++ to create a class called as employee. Data members are eid,
sal& name of the employee. Scan the data for 10 such employees & display the
same by using array of objects.

Theoretical Explanation:

This C++ program is designed to create a class named `Employee` to manage


employee data and then scan and display data for 10 employees using an array
of objects. Here's how the program works:

`Employee` Class : The `Employee` class contains three data members - `cid` for
Employee ID (integer), `sal` for Salary (double), and `name` for the Employee
Name (string).

Member Functions :

- `setData(int c, double s, string n)`: This function sets the data for an
employee object by accepting the Employee ID, Salary, and Name as
arguments. It assigns these values to the respective data members of the
object.

- `displayData()`: This function displays the data of an employee, including


the Employee ID, Name, and Salary.

`main` Function :

- In the `main` function, an array of `Employee` objects called `employees` is


created. This array can hold data for up to 10 employees.

- Using a `for` loop, the program collects data for each employee. For each
employee:
- Variables `id`, `salary`, and `empName` are declared to store the ID, salary,
and name.

- The program prompts the user to input these details, and `setData` is
called to store the data in the appropriate `Employee` object within the
`employees` array.

- A separator line is displayed to separate each employee's data.

- After collecting data for all 10 employees, a message is displayed to indicate


the beginning of the data display.

- Another `for` loop is used to display the data for all 10 employees:

- The employee number is displayed for reference.

- The `displayData` function is used to display the employee's ID, Name, and
Salary.

- A separator line is displayed to separate each employee's data.

- Finally, the program returns 0 to indicate successful execution.

Conclusion :

In conclusion, this program exemplifies the use of classes and arrays of objects
in C++. It efficiently collects and displays employee data, promoting structured
and organized data management, which is essential for applications that
handle large datasets of employee information.

Algorithm:

1. Start
2. Create a class `Employee` with data members:

- `cid` (integer): Employee ID

- `sal` (double): Salary

- `name` (string): Employee Name

3. Define public member functions within the class:

- `setData(int c, double s, string n)`: Set data for an employee object.

- `displayData()`: Display employee data.

4. In the `main` function:

- Create an array `employees` of `Employee` objects, capable of storing data


for up to 10 employees.

- Use a `for` loop to input data for each employee:

- Declare variables `id` (for ID), `salary` (for salary), and `empName`
( employee's name).

- Prompt the user to input the details for each employee, including ID,
name, and salary.

- Use `setData` to store this data within the corresponding `Employee`


object in the `employees` array.

- Display a separator line to separate each employee's data.

- Display a message to indicate the beginning of the data display.

- Use another `for` loop to display the data for all 10 employees:

- Display the employee number.

- Use the `displayData` function to display the employee's ID, name, and
salary.

- Display a separator line to separate each employee's data.

5. Return 0 to indicate successful program execution.


6. End

Source Code :

#include <iostream>
#include <string>

using namespace std;

class Employee {

public:

int cid;

double sal;

string name;

void setData(int c, double s, string n) {

cid = c;

sal = s;

name = n;

void displayData() {

cout << "Employee ID: " << cid << "\n";

cout << "Employee Name: " << name << "\n";

cout << "Salary: " << sal << "\n\n";

};

int main() {
Employee employees[10]; // Array of Employee objects

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

int id;

double salary;

string empName;

cout << "\n" << "Enter Details [ Employee " << i + 1 << " ]" << "\n";

cout << endl;

cout << "Employee ID: ";

cin >> id;

cout << "Employee Name: ";

cin.ignore(); // Clear newline from previous input

getline(cin, empName);

cout << "Salary: ";

cin >> salary;

employees[i].setData(id, salary, empName);

cout << "\n" << "---------------------------" << "\n";

}
cout <<"\n"<< "~----Display All Employee Details----~" << "\n";

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

cout << "\n" << " [ Employee " << i + 1 << " ]" << "\n";

cout << endl;

employees[i].displayData();

cout << "\n" << "---------------------------" << "\n";

return 0;

Output :
ASSIGNMENT 3
AIM: WAP in C++ to create a class called as Book. Data members are name of
the Book & price. Write default, parameterized & copy constructors to initialize
& display Book object values.

Theoretical Explanation:

This C++ program demonstrates the use of constructors in a `Book` class to


initialize and display the name and price of a book object. Here's how the
program works:

`Book` Class : The `Book` class contains two private data members - `name` and
`price`. These data members represent the name and price of a book.

Constructors :

Default Constructor : The default constructor initializes the `name` to "No


Title" and the `price` to 0.0 as default values for a book.

Parameterized Constructor : The parameterized constructor accepts two


arguments, `bookName` and `bookPrice`, which are used to initialize the
`name` and `price` of the book object, respectively.

Display Function (`display`) : This function displays the name and price of the
book using the `cout` statements.

`main` Function :
- The program starts by displaying a message indicating the beginning of the
program.

- It creates an instance of the `Book` class called `defaultBook` using the


default constructor. The `display` function is then called to display the default
values of the book, which are "No Title" for the name and 0.0 for the price.

- Next, it creates an instance of the `Book` class named `parameterizedBook`


using the parameterized constructor. This time, the book's name is set to "The
Glory," and the price is set to 687. The `display` function is called to display
these values.

- The program then demonstrates the use of a copy constructor by creating a


third instance of the `Book` class named `copyBook`. It initializes `copyBook`
with the values from `parameterizedBook`. The `display` function is used to
display the name and price of this book, which should be the same as
`parameterizedBook`.

Conclusion :

In conclusion, this program illustrates how constructors (default,


parameterized, and copy) are used to initialize objects of a class, and it
showcases how to access and display the object's data. It emphasizes the
flexibility and convenience of constructors for setting initial values of class
objects, making code more efficient and readable.

Algorithm:
1. Start

2. Create a class `Book` with private data members:

- `name` (string): Represents the name of the book.

- `price` (double): Represents the price of the book.

3. Define the following constructors within the class:

- Default Constructor:

- Sets the `name` to "No Title" and `price` to 0.0 as default values.

- Parameterized Constructor:

- Accepts two arguments, `bookName` and `bookPrice`, to initialize `name`


and `price`.

- Display Function (`display`):

- Displays the name and price of the book.

4. In the `main` function:

- Display a message indicating the beginning of the program.

- Create an instance of the `Book` class using the default constructor.

- Display the values of the book using the `display` function.

- Create another instance of the `Book` class using the parameterized


constructor, providing values for the book's name and price.

- Display the values of this book using the `display` function.

- Create a third instance of the `Book` class using the copy constructor,
initializing it with the values from the second book.

- Display the values of the third book using the `display` function.

5. End

Source Code :
#include <iostream>

#include <string>

using namespace std;

class Book

private:

string name;

double price;

public:

// Default Constructor

Book()

name = "No Title";

price = 0.0;

// Parameterized Constructor

Book(string bookName,double bookPrice)

{
name = bookName;

price = bookPrice;

// To Dislpay Name & Price

void display()

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

cout << "Book Price : " << price << endl;

cout << endl;

};

int main()

cout << endl;

cout << "All TYPE of CONSTRUCTOR"<< endl;

cout << endl;

cout << "Default Constructor"<< endl;

Book defaultBook;
defaultBook.display();

cout << "ParameteriZed Constructor "<< endl;

Book parameterizedBook("The Glory",687);

parameterizedBook.display();

cout << "Copy Constructor" << endl;

Book copyBook = parameterizedBook;

copyBook.display();

Output :

ASSIGNMENT 4
AIM: WAP in C++ to create a class called as Distance, members are ft & in.
Assign appropriate values to objects D1 & D2 and add their values by
overloading binary ‘+’ operator to store the result in D3

Theoretical Explanation:

This C++ program demonstrates the use of a `Distance` class to represent


distances in feet and inches. It allows the user to input values for two distances
(D1 and D2) and then adds these distances using the overloaded `+` operator,
storing the result in a third distance (D3).

`Distance` Class: The `Distance` class includes two private data members, `feet`
and `inches`, which represent the feet and inches components of a distance.

Member Functions:

- `readDistance()`: This function is used to input the values for the feet and
inches components of a `Distance` object. It prompts the user to enter the feet
and inches and stores these values in the corresponding data members.

- `dispDistance()`: This function displays the feet and inches components of a


`Distance` object using `cout` statements.

- Operator Overloading (`operator+`): The `+` operator is overloaded to allow


addition between two `Distance` objects. It returns a new `Distance` object
that represents the sum of the two distances. The function takes the inches
and feet of both objects, adds them, and correctly calculates the resulting feet
and inches, taking care of cases where the sum of inches exceeds 12.

`main` Function:
- The `main` function begins by creating instances of the `Distance` class: D1,
D2, and D3.

- The user is prompted to enter the values for D1 and D2 using the
`readDistance()` function. The values are stored in these objects.

- The overloaded `+` operator is used to add D1 and D2, and the resulting
distance is stored in D3.

- The total distance, stored in D3, is displayed to the user using the
`dispDistance()` function.

Conclusion :

In conclusion, this program demonstrates how to effectively use operator


overloading to add two `Distance` objects, providing a practical way to work
with distance calculations. The program highlights the use of classes and
objects to encapsulate data and behaviour, making the code more organized
and maintainable.

Algorithm:
1. Start

2. Create a class `Distance` with private data members:

- `feet` (integer): Represents the feet component of a distance.

- `inches` (integer): Represents the inches component of a distance.

3. Define public member functions within the class:

- `readDistance()`: Accepts user input for feet and inches components of a


distance.

- `dispDistance()`: Displays the values of feet and inches for a distance.

- Overload the `+` operator to perform addition between two `Distance`


objects and return the result as a new `Distance` object.

4. In the `main` function:

- Create three instances of the `Distance` class: D1, D2, and D3.

- Display a message prompting the user to enter the first distance, and call
the `readDistance()` function to input values for D1.

- Display a message prompting the user to enter the second distance, and call
the `readDistance()` function to input values for D2.

- Perform the addition of D1 and D2 using the overloaded `+` operator and
store the result in D3.

- Display the total distance stored in D3 using the `dispDistance()` function.

5. End

Source Code :
#include<iostream>

using namespace std;

class Distance {

private:

int feet, inches;

public:

void readDistance() {

cout << endl;

cout << "Enter Feet : ";

cin >> feet;

cout << "Enter Inches : ";

cin >> inches;

cout << "--------------------";

void dispDistance() {

cout << "Feet : " << feet << "\t" << "Inches : " << inches << endl;

Distance operator+(Distance& dist1) {

Distance tempD;
tempD.inches = inches + dist1.inches;

tempD.feet = feet + dist1.feet + (tempD.inches / 12);

tempD.inches = tempD.inches % 12;

return tempD;

};

int main() {

Distance D1, D2, D3;

cout << "Enter first distance : " << endl;

D1.readDistance();

cout << endl;

cout << "\nEnter Second distance : " << endl;

D2.readDistance();

cout << endl;

D3 = D1 + D2; // Perform addition

cout << "\nTotal Distance : " << endl;

D3.dispDistance();

cout << endl;


return 0;

Output :

ASSIGNMENT 5
AIM: WAP in C++ to create a class called as student, having member as roll_no
& name of the student. Create another class Exam having members as mark1 &
mark2. Finally create a class called result which is derived from student &
Exam. Write a show function in it to show student info & percentage of marks
scored using Multiple Inheritance.

Theoretical Explanation:

This C++ program demonstrates the use of multiple inheritance to create


classes for student information (`Student` class) and exam results (`Exam`
class). It derives a class called `Result` that inherits from both the `Student` and
`Exam` classes. Here's how the program works:

`Student` Class: This base class contains data members for the roll number and
name of the student. It also provides a function to display this information.

- The parameterized constructor initializes the roll number and name when
an object is created.

`Exam` Class: This second base class includes data members for marks obtained
in two exams. It also provides a function to calculate the percentage of marks.

- The parameterized constructor initializes the marks for the two exams.

`Result` Class: This derived class inherits from both the `Student` and `Exam`
classes. It combines their functionality to show student information and
calculate the percentage of marks.

- The parameterized constructor initializes data members from both base


classes.
`main` Function:

- The program starts by prompting the user to input the student's roll
number, name, and marks for the two exams.

- An instance of the `Result` class is created, and the input values are passed
to its constructor.

- The program displays a message to indicate the beginning of student result


display.

- The `Show()` function of the `Result` class is called to display the student's
information (roll number and name), marks for the two exams, and the
calculated percentage.

Conclusion :

In conclusion, this program showcases the use of multiple inheritance to


combine the features of two base classes (`Student` and `Exam`) into a derived
class (`Result`). It provides a well-structured way to handle student information
and exam results, demonstrating the principles of object-oriented
programming and data encapsulation in C++.

Source Code :
#include<iostream>

#include<string>

using namespace std;

class Student

protected:

int roll_no;

string name;

public:

Student(int r,string n):roll_no(r),name(n)

void ShowStudentInfo()

cout << "Roll No : " << roll_no << endl;

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

}
};

class Exam

protected:

float mark1,mark2;

public:

Exam(float m1, float m2):mark1(m1),mark2(m2)

float CalculatePercentage()

return ((mark1 + mark2)/ 200.0f)* 100.0f;

};

class Result : public Student, public Exam

{
public:

Result(int r, string n,float m1 , float m2):Student(r,n),Exam(m1,m2)

void Show()

ShowStudentInfo();

cout << "Marks 1 : "<< mark1 << endl;

cout << "Marks 2 : "<< mark2 << endl;

cout << "Percentage : "<< CalculatePercentage()<<"%"<<endl;

};

int main()

int rollNo;

string studentName;

float marks1,marks2;
cout << "Enter Roll NO : ";

cin >> rollNo;

cout << "Enter Name : ";

cin.ignore();

getline(cin,studentName);

cout << "Enter Marks [1] : ";

cin >> marks1;

cout << "Enter Marks [2] : ";

cin >> marks2;

Result result(rollNo,studentName,marks1,marks2);

cout << "\n Student Result : \n";

result.Show();

return 0;

Output :
ASSIGNMENT 6
AIM: WAP in C++ to demonstrate Derived class constructor.

Theoretical Explanation:

This C++ program demonstrates the use of derived class constructors in object-
oriented programming. Here's how the program works:

`Base` Class: This is the base class, which contains private data members `a`,
`b`, and `c`. It also has a constructor. The constructor initializes values for `a`
and `b,` and then calls the `swap` function to swap these values. The `swap`
function displays the values of `a` and `b both before and after swapping.

`Derived` Class: This class is derived from the `Base` class. It has a constructor
of its own. The constructor displays a message indicating that the `Derived`
class constructor is called and then calls the `add` function. The `add` function
takes two integer arguments `x` and `y` (defaulting to 5 and 7 if not provided)
and displays the result of adding these values.

`main` Function: In the `main` function, an object of the `Derived` class named
`DerivedObject` is created. A message indicating the program's start is
displayed. This object's constructor automatically calls the constructors of both
the `Base` and `Derived` classes in order.

Conclusion :
In conclusion, this program illustrates the concept of derived class constructors
and the sequence in which they are called when an object of the derived class
is created. It demonstrates how base class constructors are invoked before
derived class constructors, and how member functions can be called from
within constructors to perform specific tasks during object initialization.

Algorithm:

1. Start

2. Create a class `Base`:

- Add private data members: `a`, `b`, and `c`.

- Define a constructor for the `Base` class.

- In the constructor, display a message indicating that the `Base` class


constructor is called.

- Initialize values for `a` and `b`.

- Call the `swap` function to swap the values of `a` and `b`.

- In the `swap` function, display the values of `a` and `b before and after
swapping.

3. Create a class `Derived` derived from `Base`:

- Define a constructor for the `Derived` class.

- In the constructor, display a message indicating that the `Derived` class


constructor is called.

- Call the `add` function with default values for `x` and `y` (5 and 7,
respectively).

- In the `add` function, display the result of adding `x` and `y`.

4. In the `main` function:


- Create an object of the `Derived` class, named `DerivedObject`.

- Display a message indicating the program's start.

- The constructors for the `Base` and `Derived` classes are automatically
called, in order.

- The `add` function is called from the `Derived` class's constructor, adding
the values 5 and 7.

5. End

Source Code :
#include<iostream>

using namespace std;

class Base {

private:

int a, b, c;

public:

Base() {

cout << "Base class Constructor Called..." << endl;

a = 3;

b = 6;

swap();

void swap() {

cout << "Before Swap \n" << " A = " << a << "\n" << " B = " << b << endl;

c = a;

a = b;

b = c;

cout << "After Swap \n" << " A = " << a << "\n" << " B = " << b << endl;

}
};

class Derived : public Base {

public:

Derived() {

cout << "Derived class Constructor Called..." << endl;

add();

void add(int x = 5, int y = 7) {

cout << "Adding " << x << " and " << y << ": " << x + y << endl;

};

int main() {

Derived DerivedObject;

return 0;

Output :
ASSIGNMENT 7
AIM: WAP in C++ to implement friend function acting as a bridge between the
two classes.

Theoretical Explanation:

This C++ program demonstrates the concept of a friend function acting as a


bridge between two classes, `A` and `B`. Here's how the program works:

Class `A`: This class has a private data member, `privateA`, and a constructor
that initializes this private member. It declares the `bridgeFunction` as a friend,
allowing it to access the private members of `A`.

Class `B`: Similar to class `A`, it has a private data member, `privateB`, and a
constructor to initialize it. It also declares the `bridgeFunction` as a friend

`bridgeFunction`: This is a global function and not a member of either class. It


takes two parameters: an object of class `A` and an object of class `B`. It can
access the private members of both classes due to the friend declarations. The
function prints the values of `privateA` and `privateB`.

`main` Function: In the `main` function, objects `objA` and `objB` of classes `A`
and `B` are created and initialized with values. Then, the `bridgeFunction` is
called with these objects as arguments. The function accesses and prints the
private members of both classes, effectively demonstrating how the friend
function bridges the gap between the two classes, allowing them to access
each other's private members.

Conclusion :

In conclusion, this program showcases the use of a friend function to enable


access to private members of different classes. It exemplifies how the friend
function can act as a bridge, facilitating interaction between classes that would
not normally be able to access each other's private members

Algorithm:
1. Start

2. Create a class `A`:

- Add a private data member, `privateA`.

- Define a parameterized constructor for `A` that initializes the private


member.

- Declare a friend function, `bridgeFunction`, which allows it to access the


private members of class `A`.

3. Create a class `B`:

- Add a private data member, `privateB`.

- Define a parameterized constructor for `B` that initializes the private


member.

- Declare the same friend function, `bridgeFunction`, which allows it to access


the private members of class `B`.

4. Define the `bridgeFunction`:

- This is a global function, not a member of either class.

- It takes two objects, one of class `A` and one of class `B`, as parameters.

- In this function, it accesses the private members `privateA` from class `A`
and `privateB` from class `B` and prints their values.

5. In the `main` function:

- Create objects of class `A` and class `B`, named `objA` and `objB`, and
initialize them with values.

- Call the `bridgeFunction` with these two objects as arguments.

- The `bridgeFunction` accesses and prints the private members of both


classes.

6. End

Source Code :
#include <iostream>;

using namespace std;

class B;

class A {

private:

int privateA;

public:

A(int a) : privateA(a) {}

friend void bridgeFunction(A, B);

};

class B {

private:

int privateB;

public:

B(int b) : privateB(b) {}

friend void bridgeFunction(A, B);

};
void bridgeFunction(A objA, B objB) {

cout << "Accessing privateA from class A: " << objA.privateA << endl;

cout << "Accessing privateB from class B: " << objB.privateB << endl;

int main() {

A objA(10);

B objB(20);

bridgeFunction(objA, objB);

return 0;

Output :

ASSIGNMENT 8
AIM: WAP in C++ to implement Virtual function for function overriding.

Theoretical Explanation:

This C++ program demonstrates the concept of virtual functions for function
overriding, enabling polymorphism. Here's how the program works:

Base Class `base`: This class contains a public virtual function `print()`, which is
designed to be overridden by derived classes. It also has a public non-virtual
function `show()`.

Derived Class `derived`: This class inherits publicly from the `base` class and
overrides the virtual function `print()`. It also defines a non-virtual function
`show()`.

`main` Function: In the `main` function, the following steps are performed:

- A pointer to the base class, `bptr`, is declared.

- An object of the derived class, `d`, is created.

- The address of the derived class object `d` is assigned to the base class
pointer `bptr`.

- The `print()` function is called using the base class pointer `bptr`. Since it's
declared as virtual in the base class and overridden in the derived class, the
overridden version in the derived class is executed at runtime. This is an
example of dynamic polymorphism or late binding.

- The `show()` function is called using the base class pointer `bptr`. However,
since `show()` is not declared as virtual in the base class, the function call is
resolved at compile-time, and the base class's version of `show()` is executed.
This is an example of static polymorphism or early binding.

Conclusion :

In conclusion, this program illustrates the use of virtual functions for function
overriding, allowing a derived class to provide its own implementation of a
function declared in a base class. It demonstrates how virtual functions enable
polymorphism, enabling the selection of the appropriate function to call at
runtime.

Algorithm:
1. Start

2. Create a base class `base`:

- Declare a public virtual function `print()` in the base class. This function can
be overridden by derived classes.

- Define a public non-virtual function `show()` in the base class.

3. Create a derived class `derived`:

- Inherit publicly from the base class, indicating that `derived` is a derived
class.

- Override the virtual function `print()` in the derived class. The overridden
function in the derived class has the same name and parameters as the base
class.

- Define a public non-virtual function `show()` in the derived class. This


function has the same name and parameters as the base class's `show()`
function but does not override it.

4. In the `main` function:

- Declare a pointer to the base class, `bptr`.

- Create an object of the derived class, `d`.

- Assign the address of the derived class object `d` to the base class pointer
`bptr`.

- Call the `print()` function using the base class pointer `bptr`. Since the
`print()` function is declared as virtual in the base class and overridden in the
derived class, the function call is resolved at runtime, and the derived class's
version of `print()` is executed.

- Call the `show()` function using the base class pointer `bptr`. Since the
`show()` function is not declared as virtual in the base class, the function call is
resolved at compile-time, and the base class's version of `show()` is executed.

5. End.

Source Code :
#include<iostream>

using namespace std;

class base

public:

virtual void print()

cout<<"Print base class\n";

void show()

cout<<"show base class\n";

};

class derived:public base

public:

void print()

cout<<"Print Derived Class\n";


}

void show()

cout<<"Show Derived Class\n";

};

int main()

base *bptr;

derived d;

bptr= &d;

bptr -> print();

bptr -> show();

return 0;

Output :
ASSIGNMENT 9
AIM:WAP in C++ to overload insertion (>>) & extraction (<<) operators for
objects.

Theoretical Explanation:

This C++ program demonstrates operator overloading for insertion (`>>`) and
extraction (`<<`) operators for objects of the `Complex` class. Here's how the
program works:

Complex Class: The `Complex` class represents complex numbers with real and
imaginary parts. It contains private data members `real` and `img`, a
parameterized constructor to set these values, and the overloaded `>>` and
`<<` operators.

Overloaded `>>` Operator: The `>>` operator is overloaded as a friend function.


It takes an `istream` object and a `Complex` object as parameters. It prompts
the user to enter the real and imaginary parts of the complex number, reads
these values from the input stream, and sets them in the `Complex` object.
This operator returns the input stream to allow for chaining.

Overloaded `<<` Operator: The `<<` operator is also overloaded as a friend


function. It takes an `ostream` object and a constant `Complex` object as
parameters. It formats the output by writing the real part and handling the
sign of the imaginary part (+i for positive, -i for negative). This operator returns
the output stream to allow for chaining.
`main` Function: In the `main` function, an object `c1` of the `Complex` class is
created with default values. The user is prompted to enter a complex number
using the overloaded `>>` operator. The entered complex number is then
displayed using the overloaded `<<` operator, providing a more intuitive
format for complex numbers.

Conclusion :

In conclusion, this program demonstrates the use of operator overloading to


make it more convenient and intuitive for the user to input and output
complex numbers in a user-friendly format. The `>>` and `<<` operators have
been overloaded to work with objects of the `Complex` class, making complex
number manipulation more straightforward.

Algorithm:
1. Start

2. Create a `Complex` class:

- Define private data members, `real` for the real part and `img` for the
imaginary part, both initialized to 0 by default.

- Declare a parameterized constructor to set the values of `real` and `img`


when an object is created.

- Declare the overloaded insertion (>>) and extraction (<<) operators as


friend functions, which allow them to access the private members of the
`Complex` class.

3. Overload the `>>` operator:

- Define a function that takes an `istream` object `in` and a `Complex` object
`c` as arguments.

- Prompt the user to enter the real and imaginary parts of the complex
number.

- Read the values from the input stream and set them in the `Complex` object
`c`.

- Return the input stream `in` to allow for chaining.

4. Overload the `<<` operator:

- Define a function that takes an `ostream` object `out` and a constant


`Complex` object `c` as arguments.

- Write the real part to the output stream.

- Determine whether the imaginary part is positive or negative and format it


accordingly (e.g., +i for positive, -i for negative).

- Return the output stream `out` to allow for chaining.

5. In the `main` function:


- Create a `Complex` object `c1` with default values.

- Prompt the user to enter a complex number and use the overloaded `>>`
operator to read the input.

- Use the overloaded `<<` operator to display the complex object with a more
intuitive format.

6. End

Source Code :
#include <iostream>

using namespace std;

class Complex {

private:

int real, img;

public:

Complex(int r = 0, int i = 0) {

real = r;

img = i;

friend istream& operator>>(istream& in, Complex& c);

friend ostream& operator<<(ostream& out, const Complex& c);

};

istream& operator>>(istream& in, Complex& c) {

cout << "Enter Real Part: ";

in >> c.real;

cout << "Enter Imaginary Part: ";

in >> c.img;

return in;
}

ostream& operator<<(ostream& out, const Complex& c) {

out << c.real;

if (c.img >= 0) {

out << "+i" << c.img;

} else {

out << "-i" << -c.img;

return out;

int main() {

Complex c1;

cout << "Enter a Complex Number" << endl;

cin >> c1;

cout << "The complex Object is: " << c1 << endl;

return 0;

Output :
ASSIGNMENT 10
AIM: WAP to implement function Template.

Theoretical Explanation:

This C++ program showcases the use of function templates, which are a
powerful feature of C++ that allows you to write generic functions that work
with different data types.

Function Template Definition: The program defines a function template called


`myMax`. This function template is defined with the template parameter `T`,
which represents a generic data type. The function template takes two
parameters of type `T`, `x` and `y`. Inside the function template, it uses a
ternary conditional operator to compare `x` and `y` and returns the maximum
of the two values.

In the `main` Function:

- The `main` function demonstrates the use of the `myMax` function


template with different data types:

- It calls `myMax<int>(3, 7)` to find the maximum of two integers, 3 and 7,


and displays the result.

- It calls `myMax<double>(3.0, 7.0)` to find the maximum of two double-


precision floating-point numbers, 3.0 and 7.0, and displays the result.

- It calls `myMax<char>('g', 'e')` to find the maximum of two characters, 'g'


and 'e', and displays the result.
The function template `myMax` is instantiated with the appropriate data type
(int, double, or char) based on the arguments passed, and it works seamlessly
with these different data types. This demonstrates the flexibility and
reusability of function templates in C++.

Conclusion :

In conclusion, this program showcases the power of function templates,


enabling the creation of generic functions that can work with various data
types, providing code flexibility and reusability.
Algorithm:

1. Start

2. Define a function template `myMax`:

- The function template is defined with the template parameter `T`.

- It takes two parameters of type `T`, named `x` and `y`.

- Inside the function, a ternary conditional operator (`? :`) is used to compare
`x` and `y`. If `x` is greater than `y`, it returns `x`; otherwise, it returns `y`.

- The result is of type `T`, making this function template capable of working
with various data types.

3. In the `main` function:

- Use the `myMax` function template to find the maximum of two values of
different data types:

- Find the maximum of two integers (3 and 7) by calling `myMax<int>(3, 7)`


and display the result.

- Find the maximum of two double-precision floating-point numbers (3.0


and 7.0) by calling `myMax<double>(3.0, 7.0)` and display the result.

- Find the maximum of two characters ('g' and 'e') by calling


`myMax<char>('g', 'e')` and display the result.

4. End

Source Code :
#include<iostream>

using namespace std;

template <typename T> T myMax(T x, T y)

{return (x > y) ? x : y;}

int main()

cout << "\t" << myMax<int>(3, 7) << endl;

cout << "\t" << myMax<double>(3.0, 7.0) << endl;

cout << "\t" << myMax<char>('g', 'e') << endl;

return 0;

Output :

You might also like