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

Oops Lab Vaseem

The document describes an experiment to create an Employee class with data members Empnumber and Empname, and member functions getdata() and datadisplay(). A main() function is written to: 1) Create an array of Employee objects of size n, where n is input by the user 2) Input name and employee number for each object using getdata() 3) Display the details of each employee by calling datadisplay()

Uploaded by

Mohd. Vaseem
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)
219 views

Oops Lab Vaseem

The document describes an experiment to create an Employee class with data members Empnumber and Empname, and member functions getdata() and datadisplay(). A main() function is written to: 1) Create an array of Employee objects of size n, where n is input by the user 2) Input name and employee number for each object using getdata() 3) Display the details of each employee by calling datadisplay()

Uploaded by

Mohd. Vaseem
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/ 41

Object Oriented Programming -(SE 203)

LAB FILE

Submitted by – Mohd. Vaseem(2K21/SE/117)

Submitted to - Mr. Ram Murti Rawat

DEPARTMENT OF SOFTWARE ENGINEERING


DELHI TECHNOLOGICAL UNIVERSITY, SHAHBADDAULATPUR
(FORMERLY DELHI COLLEGE OF ENGINEERING)MAIN BAWANA ROAD, Delhi
110042

1
INDEX

S.NO. EXPERIMENTS DATE


1. Write a program to write function overloading.
Program that gives sum of two numbers.
Write a C++ program to print your personal details name,surname
2. (single character), total marks, gender(M/F), result(P/F) by taking input
from the user.
1) Create a class called Employee that has “Empnumber‟and
“Empname‟ as data members and member functionsgetdata( ) to input
data display() to output data. Write a main function to create an array of
‟Employee‟ objects. Accept and print the details of at least 6 employees.
3.
2) Write a program to implement a class called ComplexNumber and
write a function add() to add two
complex numbers.

Write a C++ program to swap two number by both call by value and call by
reference mechanism, using two functionsswap_value() and
4. swap_reference respectively , by getting the choice from the user and
executing the user’s choice by switch-case.

Write a C++ program to create a simple banking system in which the initial
balance and the rate of interest are read from the keyboard and these
values are initialized using theconstructor. The destructor member
function is defined in this program to destroy the class object created
using constructor member function. This program consists of following
member functions:
i. Constructor to initialize the balance and rate of interest
5. ii. Deposit - To make deposit
iii. Withdraw – To with draw an amount
iv. Compound – To find compound interest
v. getBalance – To know the balance amount
vi. Menu – To display menu options
vii. Destructor

Write a program to accept five different numbers by creating a class called


friendfunc1 and friendfunc2 taking 2and 3 arguments respectively and
6. calculate the average of these numbers by passing object of the class to
friend function.
Write a program to accept the student detail such as name and 3 different
marks by get_data() method and display the nameand average of marks using
7. display() method. Define a friend class for calculating the average of marks
using the method mark_avg().

Write a C++ program to perform different arithmetic operation such as


addition, subtraction, division, modulus and multiplication using inline function.
8.

2
9. WAP to return absolute value of variable types integer andfloat using
function overloading.

WAP to perform string operations using operatoroverloading


in C++
10. i. = String Copy
ii. ==,>,< Equality
iii. + Concatenation

Consider a class network of figure given below. The class master derives
information from both account and admin classes which in turn derive
information from the class person. Define all the four classes and write a
program to create, update and display the information contained in master
objects. Also demonstrate the use of different access specifiers by means of
member variables and member functions.

11.

Write a C++ program to create three objects for a class named pntr_obj with
data members such as roll_no and name. Createa member function set_data()
12. for setting the data values and print() member function to print which object
has invoked itusing ‘this’ pointer

Write a C++ program to explain virtual function (polymorphism) by creating


a base class c_polygon which has virtual function area(). Two classes
c_rectangle and c_triangle derived from c_polygon and they have area() to
13.
calculate and return the area of rectangle and triangle respectively.

Write a program to explain class template by creating a template T for a


class named pair having two data members of type T which are inputted by a
constructor and a member function get-max() return the greatest of two
14.
numbers to
main. Note: the value of T depends upon the data typespecified during object
creation.

Write a C++ program to illustrate:


i. Division by zero
15.
ii. Array index out of bounds exceptionAlso use
multiple catch blocks.

3
EXPERIMENT-2
AIM - Write a C++ program to print your personal details name, surname (single character), total
marks, gender(M/F), result(P/F) by taking input from the user.
THEORY - Class: A class in C++ is the building block, that leads to Object- Oriented programming. It is
a user-defined data type, which holds its own data members and member functions, which can be
accessed and used by creating aninstance of that class. A C++ class is like a blueprint for an object.
A Class is a user defined data-type which has data members and memberfunctions.
• Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
defines the properties and behavior ofthe objects in a Class.
An Object is an instance of a Class. When a class is defined, no memory isallocated but when it is
instantiated (i.e. an object is created) memory is allocated.
get() function is used to take the data input from the user and store in the data members of the
class, put() function is used to display the data stored in thesedata members.
CODE
#include<bits/stdc++.h>
using namespace std;
class details
{
int marks;
char gender , result;
char first_name[20];
char last_name [20];
public :
void get()
{
cout<<"Enter your first name - ";
gets(first_name);
cout<<"Enter your last name - ";
cin>>last_name;
cout<<"Enter your marks out of 100 - ";
cin>>marks;
if( marks>=33)
result = 'P';
else

4
result = 'F';
cout<<"Enter your gender - M/F ";
cin>>gender;
return;

}
void put()
{
cout<<"First name - "<<first_name<<endl;
cout<<"First letter of last name - "<<last_name[0]<<endl;
cout<<"Total marks = "<<marks<<endl;
cout<<"Result is - "<<result<<endl;
cout<<"Gender is - "<<gender;
}

};

int main()
{
details s;
s.get();
s.put();
return 0;
}
OUTPUT

LEARNING AND FINDINGS: By the above experiment we were able to learn and implement concepts of classes and
objects. Class is a feature of object oriented programming through which we are able to solve problems in real
world. Here we made class details having data members marks, gender ,result , first name, last name.

5
EXPERIMENT – 3
AIM - Create a class called 'Employee' that has “Empnumber‟ and “Empname‟as data members and
member functions getdata( ) to input datadisplay() to output data. Write a main function to create an
array of ‟Employee‟ objects.
Accept and print the details of at least 6 employees.
THEORY - A Class is a user defined data-type which has data members and member functions. Data
members are the data variables and member functionsare the functions used to manipulate these
variables and together these data members and member functions defines the properties and
behavior of the objects in a Class.
An Object is an instance of a Class. When a class is defined, no memory isallocated but when it
is instantiated (i.e. an object is created) memory is allocated.
getdata() function is used to take the data input from the user and store in thedata members of
the class, displaydata() function is used to display the data stored in these data members.
User defined data types like classes and structures can be used similar toprimitive data types and
can be used to create variables and arrays.
CODE
#include<iostream>
using namespace std;
class Employee
{
int Empnumber;
string Empname;
public :
void getdata( int num , string name)
{
Empnumber = num;
Empname = name;
return;
}
void datadisplay()
{
cout<<"Name is - "<<Empname<<endl;
cout<<"Employee number is - "<<Empnumber<<endl;
return;
}
};
int main()
{
int n;
cout<<"Enter the number of employees who details are to be displayed- ";
cin>>n;
int num;
string name;
Employee arr[n];

6
for( int i = 0 ; i<n ; i++)
{
cout<<"Enter name - ";
cin>>name;
cout<<"Enter employee number - ";
cin>>num;

arr[i].getdata( num , name);


}
cout<<endl;
for( int i = 0 ; i<n ; i++)
{
arr[i].datadisplay();
cout<<endl;
}
return 0;

}
OUTPUT

LEARNING AND FINDINGS: By the above experiment we were able to learn and implement concepts of classes and
objects. Class is a feature of object oriented programming through which we are able to solve problems in real
world. Here we made class employee having employee number, name and we used getter setter function.

7
EXPERIMENT-4
AIM - Write a C++ program to swap two number by both call by value and callby reference
mechanism, using two functions swap_value() and swap_reference
respectively, by getting the choice from the user and executing the user’schoice by switch-case.
THEORY - Call By Value: In this parameter passing method, values of actualparameters are copied
to function’s formal parameters and the two types of parameters are stored in different memory
locations. So any changes made inside functions are not reflected in actual parameters of the
caller.
Call by Reference: Both the actual and formal parameters refer to the same locations, so any
changes made inside the function are actually reflected inactual parameters of the caller.
CODE
#include<iostream>
using namespace std;
void swap_value( int a , int b)
{
int temp;
temp = a;
a=b;
b= temp;
cout<<"After swapping a = "<<a<<" and b = "<<b;
return ;
}
void swap_reference( int *a , int *b)
{
int temp;
temp = *a;
*a= *b;
*b = temp;
cout<<"After swapping a = "<<*a<<" and b = "<<*b;
return ;
}
int main()
{
int a,b;
cout<<"Enter the value of a - ";
cin>>a;
cout<<"Enter the value of b - ";
cin>>b;
cout<<"Before swapping a = "<<a<<" and b = "<<b<<endl;
cout<<"1. Swap using call by value"<<endl;
cout<<"2. Swap using call by reference"<<endl;
cout<<"Enter your choice - ";

8
int n;
cin >>n;
switch(n)
{
case 1 :
swap_value(a , b);
break;
case 2 :
swap_reference( &a , &b);
break;
default :
cout<<"wrong input!";
}
return 0;

}
OUTPUT

LEARNING AND FINDINGS: We learned to swap two numbers by call by reference and call by value and we gave
the user the choice of using any of the mentioned method.

9
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 keyboard and these values are initialized using the constructor.
The destructor member function isdefined in this program to destroy the class object created
using constructor member function. This program consists of following member functions-

1. Constructor to initialize the balance and rate of interest


2. Deposit - To make deposit
3. Withdraw – To with draw an amount
4. Compound – To find compound interest
5. getBalance – To know the balance amount
6. Menu – To display menu options
7. Destructor

THEORY - Constructor: A constructor is a member function of a class that hasthe same name as the
class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is
used to allocate the memory to an object of the class. It is called whenever an instance of the class is
created. It can be defined manually with arguments or without arguments. There can be many
constructors in class. It can be overloaded but it can not be inherited or virtual. There is a concept of
copy constructor which is used to initialize a object from another object.
Syntax:
ClassName()
{
//Constructor's Body
}
Destructor: Like constructor, deconstructor is also a member function of a class that has the same
name as the class name preceded by a tilde(~) operator. It helps to deallocate the memory of an
object. It is called while object of the class is freed or deleted. In a class, there is always a single
destructor without any parameters so it can’t be overloaded. It is always called in the reverse order
of the constructor. if a class is inherited by another class and both the classes have a destructor
then the destructor of the child class is called first, followed by the destructor of the parent or base
class.
Syntax:

10
~ClassName()
{
}
CODE
#include <iostream>
using namespace std;
#include<cmath>
class Bank{
float amount ;
float roi;
public:
Bank(float a , float b){
amount = a;
roi = b;
}
void withdraw()
{
int money;
cout << "Enter amount to withdraw " << endl;
cin >> money;
if(money> amount)
{
cout << "Insufficient Balance" << endl;
}
else
{
amount -= money;
cout << "Your Balance is : " << amount;
}
}
void getBalance(){
cout << "Your Balance is : " << amount;
}
void deposit(){
int money;
cout << "Enter amount to deposit " << endl;
cin >> money;
amount += money;
cout << "Your Balance is : " << amount;
}
void compound(){
float time;
cout << "Enter time duration" << endl;
cin >> time;
int compountInterest = (amount) * (pow((1 + (roi/100)),
time));
cout << "Compount Interest is : " << compountInterest <<
endl;
}

11
void menu(){
cout << " \n\n1.Deposit Money\n2.WithdrawMoney\n3.Calculate Compound Interest\
n4.Balance\n5.Destructor\nEnter the Number : " << endl;
}
~Bank()
{
cout << "Destructor called" << endl;
}
};
int main()
{
float a=0, b = 2;
Bank s(a, b);
s.menu();
int number;
cin >> number;
while(number != 5){
switch (number)
{
case 1 :
s.deposit();
break;
case 2 :
s.withdraw();
break;
case 3:
s.compound();
break;
case 4:
s.getBalance();
break;
case 5:
cout << "You have quit the system succesfully";
return 0;
default:
cout << "Invalid operation!! Please try again" <<
endl;
break;
}
s.menu();
cin >> number;
}
cout << "You have quit the system succesfully" << endl;
return 0;
}

12
OUTPUT

LEARNING AND FINDINGS: By the above experiment we were able to learn and implement concepts of classes and
objects. Class is a feature of object oriented programming through which we are able to solve problems in real
world. Here we learned about constructors and destructors.

13
EXPERIMENT - 6
AIM - Write a program to accept five different numbers by creating a class called friendfunc1 and
friendfunc2 taking 2 and 3 arguments respectively andcalculate the average of these numbers by
passing object of the class to friendfunction.
THEORY - Friend Class A friend class can access private and protected members of other class in
which it is declared as friend. It is sometimes usefulto allow a particular class to access private
members of other class. For example, a LinkedList class may be allowed to access private
members of Node.
Friend Function Like friend class, a friend function can be given a special grantto access private and
protected members. A friend function can be:
a) A member of another class
b) A global function
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. too many functions or external classes are
declared as friends of a class with protected or private data,it lessens the value of encapsulation of
separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become afriend of A
automatically.
3) Friendship is not inherited.
CODE
#include<iostream>
using namespace std;
class friendFunc2;
class friendFunc1
{

int a1,a2;
public:
friendFunc1(int x,int y)
{
a1=x;
a2=y;
}
friend float average(friendFunc1 f1,friendFunc2 f2);
};
class friendFunc2
{

14
int a3,a4,a5;
public:
friendFunc2(int x,int y,int z)
{
a3=x;
a4=y;
a5=z;
}
friend float average(friendFunc1 f1,friendFunc2 f2);
};
float average(friendFunc1 f1, friendFunc2 f2)
{
return (f1.a1 + f1.a2 + f2.a3 + f2.a4 + f2.a5) / 5.0;
}
int main()
{
int a,b,c,d,e;
cout<<"Enter the numbers - ";
cin>>a>>b>>c>>d>>e;
friendFunc1 obj1(a,b);
friendFunc2 obj2(c,d,e);
float ans = average(obj1, obj2);
cout << "Average : " << ans << endl;
return 0;
}
OUTPUT

LEARNING AND FINDINGS: By the above experiment we were able to learn and implement concepts of classes and
objects. Class is a feature of object oriented programming through which we are able to solve problems in real
world. Here we created a friend function which is able to access the private data members of the class to which it
is a friend.

15
EXPERIMENT – 7
AIM - Write a program to accept the student detail such as name and 3 differentmarks by get_data()
method and display the name and average of marks using display() method. Define a friend class for
calculating the average of marks using the method mark_avg().
THEORY - Friend Class A friend class can access private and protected members of other class in
which it is declared as friend. It is sometimes usefulto allow a particular class to access private
members of other class. For example, a LinkedList class may be allowed to access private
members of Node.
CODE
#include<iostream>
using namespace std;
class student
{
int x , y , z;
string s;
public :
void get_data( int a, int b , int c , string k)
{ x = a;
y = b;
z = c;
s = k;
return;
} void put_data()
{
cout<<"The name of the student is - "<<s<<endl;
cout<<"The marks of the student are - "<<x<<" , "<<y<<" , "<<z<<endl;
}
friend float mark_avg( student m);
};
float mark_avg( student n)
{
return (n.x + n.y + n.z)/3.0;
}
int main()
{
student stu;
int a, b ,c;
string name;
cout<<"Enter the name of the student - ";
cin>>name;
cout<<"Enter the marks of the student - ";
cin>>a>>b>>c;
stu.get_data(a,b,c,name);
stu.put_data();
cout<<"The average marks of "<<name<<" are - "<<mark_avg(stu);
return 0;
}

16
OUTPUT

LEARNING AND FINDINGS: By the above experiment we were able to learn and implement concepts of classes and
objects. Class is a feature of object oriented programming through which we are able to solve problems in real
world. Here we took input of student’s detail to calculate the average marks. We also learned about getter and
setter.

17
EXPERIMENT – 8
AIM - Write a C++ program to perform different arithmetic operation such asaddition, subtraction,
division, modulus and multiplication using inline function.
THEORY- C++ provides an inline functions to reduce the function call overhead. Inline function
is a function that is expanded in line when it is called. When the inline function is called whole
code of the inline functiongets inserted or substituted at the point of inline function call. This
substitution is performed by the C++ compiler at compile time. Inline function may increase
efficiency if it is small.
The syntax for defining the function inline is:inline return-type
function-name(parameters)
{
// function code
}
CODE
#include<iostream>
using namespace std;
class operations
{
int i , j;
public :
void get_data(int a , int b)
{
i = a;
j = b;
return;
}
void put_data()
{
cout<<"a = "<<i<<endl;
cout<<"b = "<<j<<endl;
return;
}
inline int add()
{
return i+j;
}
inline int subtract()
{
return i-j;
}
inline int multiply()
{

18
return i*j;
}
inline int divide()
{
return i/j;
}
inline int modulus()
{
return i%j;
}
};
int main()
{ operations op;
cout<<"Enter the numbers - ";int a , b;
cin>>a>>b; op.get_data(a,b);
op.put_data(); cout<<"MENU - "<<endl;
fn1 :
int x;
cout<<"1. Add"<<endl; cout<<"2. Subtract"<<endl;
cout<<"3. Multiply"<<endl; cout<<"4. Divide"<<endl;
cout<<"5. Modulus"<<endl; cout<<"6. Exit"<<endl;
cout<<"Enter your choice - ";cin>>x;
switch (x)
{
case 1 :
{
cout<<"a + b = "<<op.add()<<endl;goto fn1;
}
case 2 :
{
cout<<"a - b = "<<op.subtract()<<endl;goto fn1;
}
case 3 :
{
cout<<"a * b = "<<op.multiply()<<endl;goto fn1;
}
case 4 :
{
cout<<"a / b = "<<op.divide()<<endl;
goto fn1;
}
case 5 :
{
cout<<"a % b = "<<op.modulus()<<endl;
goto fn1;
}
case 6 :
{ return 0;}}}

19
OUTPUT

LEARNING AND FINDINGS: By the above experiment we were able to learn and implement concepts of classes and
objects. Class is a feature of object oriented programming through which we are able to solve problems in real
world. Here we made class operations which included arithmetic operation.

20
EXPERIMENT-9
AIM-WAP to return absolute value of variable types integer and float usingfunction overloading.
THEORY - Function overloading is a feature of object oriented programmingwhere two or more
functions can have the same name but different parameters. When a function name is overloaded
with different jobs it is called Function Overloading. In Function Overloading “Function” name should
be the same and the arguments should be different. Function overloading can be considered as an
example of polymorphism feature in C++.
How Function Overloading works?
• Exact match:- (Function name and Parameter)
• If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
• If no match found:
->C++ tries to find a match through the standard conversion.

• ELSE ERROR
CODE
#include<bits/stdc++.h>
using namespace std;
int absolute(int m)
{
if(m>=0)
return m;
else
return -m;
}
float absolute(float m)
{
if(m>=0)
return m;
else
return -m;
}
int main()
{
cout<<"Enter the value of integer - ";
int x;
cin>>x;
cout<<"The absolute value of "<<x<<" is = "<<absolute(x)<<endl;

21
cout<<"Enter the value of float - ";
float y;
cin>>y;
cout<<"The absolute value of "<<y<<" is = "<<absolute(y)<<endl;
return 0;
}
OUTPUT

LEARNING AND FINDINGS. Here we learned to do WAP to return absolute value of variable types integer and
float using function overloading. Function overloading means to make functions having same name performing
different task.

22
EXPERIMENT – 10
AIM - WAP to perform string operations using operator overloading in C++
1. String Copy
2. ==,>,<, Equality
3. + Concatenation
THEORY - In C++, we can make operators to work for user defined classes. This means C++ has the
ability to provide the operators with a special meaningfor a data type, this ability is known as
operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that wecan concatenate two
strings by just using +.
Other example classes where arithmetic operators may be overloaded areComplex Number,
Fractional Number, Big Integer, etc.
Operator functions are same as normal functions. The only differences are, name of an operator
function is always operator keyword followed by symbol ofoperator and operator functions are called
when the corresponding operator is used.
Almost all operators can be overloaded except few. Following is the list ofoperators that
cannot be overloaded.
. (dot) ?: :: sizeof
Important points about operator overloading
1) For operator overloading to work, at least one of the operands must be a userdefined class
object.
2) Assignment Operator: Compiler automatically creates a default assignmentoperator with every
class. The default assignment operator does assign all members of right side to the left side and
works fine most of the cases (this behaviour is same as copy constructor). See this for more
details.
3) Conversion Operator: We can also write conversion operators that can beused to convert
one type to another type.
Overloaded conversion operators must be a member method. Other operatorscan either be
member method or global method.
4) Any constructor that can be called with a single argument works as a conversion constructor,
means it can also be used for implicit conversion to theclass being constructed.
CODE
#include <iostream>
#include <stdio.h> //for gets() and puts()
#include <string.h>
using namespace std;

23
class String{
string str;

public:
String()
{
str = "";
}
String(string s)
{
str = s;
}
void operator=(String s); String
operator+(String s);bool operator==(String s);
bool operator<(String s); bool operator>(String
s); void show();
};

void String :: operator=(String s){ cout << "Operator


Overloaded=\n";str = s.str;
}

String String :: operator+(String s){String temp;


cout << "Operator Overloaded+\n";temp.str = str + s.str;
return temp;
}

bool String :: operator==(String s)


{
cout<<"Operator overloaded == "<<endl;if (str == s.str)
return true;return
false;
}

bool String :: operator<(String s){ cout<<"Operator overloaded < "<<endl;


int x = min(str.size(), s.str.size());for (int i = 0; i < x; i++)
{
if (str[i] < s.str[i])return true;

24
else if(str[i] > s.str[i])
return false;
}
return false;
}

bool String :: operator>(String s){


cout<<"Operator overloaded > "<<endl;
int x = min(str.size(), s.str.size());
for (int i = 0; i < x; i++)
{
if (str[i] > s.str[i])
return true;
else if(str[i] < s.str[i])
return false;
}
return false;
}

void String :: show(){


cout << str << "\n";
}

int main(){
String s1("Priyanshi"), s2("Anand"), ch;
cout<<"String s1 - ";
s1.show();
cout<<"String s2 - ";
s2.show();
s1 = s1 + s2;
ch = s1;
cout<<"String s1 after concatenation - ";
s1.show();
ch.show();
if(s1 < s2)
cout <<"s2 is longer than s1!";
else
cout <<"s1 is longer than s2!";
return 0;
}

25
OUTPUT

LEARNING AND FINDINGS. Here we learned to do operator overloading to perform operations on string.
Operator overloading is a form of polymorphism. In this same operators when operate upon different operands
Perform different operations.

26
EXPERIMENT – 11
AIM - Consider a class network of figure given below. The class master derives information from
both account and admin classes which in turn derive information from the class person. Define all
the four classes and write a program to create, update and display the information contained in
master objects. Also demonstrate the use of different access specifiers by means of member
variables and member functions.

THEORY - In C++, inheritance is a process in which one object acquires all the properties and
behaviours of its parent object automatically. In such way, you can reuse, extend or modify the
attributes and behaviours which are defined in otherclass.
In C++, the class which inherits the members of another class is called derived class and the class
whose members are inherited is called base class. The derived class is the specialized class for the
base class.
Advantage of C++ Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no need to define
the member again. So, less code is required in the class.
Types Of Inheritance
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.The Syntax of
Derived class:
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}

27
Where,
derived_class_name: It is the name of the derived class.
visibility mode: The visibility mode specifies whether the features of the baseclass are publicly
inherited or privately inherited. It can be public or private. base_class_name: It is the name of the
base class.
o When the base class is privately inherited by the derived class, public members of the base
class become the private members of the derived class. Therefore, the public members of the
base class are not accessible bythe objects of the derived class only by the member functions of
the derivedclass.
o When the base class is publicly inherited by the derived class, public members of the base
class also become the public members of the derived class. Therefore, the public members of
the base class are accessible by the objects of the derived class as well as by the member
functions of the baseclass.
Note:
o In C++, the default mode of visibility is private.
o The private members of the base class are never inherited.
CODE
#include<iostream>
using namespace std;
class person{
private:
string name;
int code;
public:
person(string s, int c){
name = s;
code = c;
cout<<"\nPerson constructor called";
}
void display();
void updateName(string);
void updateCode(int);
};
class account: virtual public person{
private:
int pay;
public:
account(string s, int c, int p):person(s, c){
pay = p;
cout<<"\nAccount constructor called";
}
void display();
void updatePay(int);
};

28
class admin: virtual public person{private:
int experience;

public:
admin(string s, int c, int exp):person(s, c){experience = exp;
cout<<"\nAdmin constructor called";
}
void display(); void
updateExp(int);
};
class master: public account, public admin{public:
master(string s, int c, int p, int
exp):account(s,c,p),admin(s,c,exp),person(s, c){
cout<<"\nMaster constructor called";
}
void update(); void display();
};
void person :: display(){ cout<<"\nName =
"<<name;cout<<"\nCode = "<<code;
}
void person :: updateName(string s){name = s;
}
void person :: updateCode(int n){code = n;
}
void account :: display(){cout<<"\nPay =
"<<pay;
}
void account :: updatePay(int n){pay = n;
}
void admin :: display(){ cout<<"\nExperience = "<<experience;
}
void admin :: updateExp(int n){experience = n;
}
void master :: update(){
//this->display(); cout<<"\n\nUPDATE
DETAILS";string n;
int c, p, exp;

29
cout<<"\nName = ";
cin>>n;
cout<<"\nCode = ";
cin>>c;
cout<<"\nPay = ";
cin>>p;
cout<<"\nExperience = ";
cin>>exp;
updateName(n);
updateCode(c);
updatePay(p);
updateExp(exp);
}
void master :: display(){
cout<<"\n\nMASTER DETAILS";
person::display();
account::display();
admin::display();
}
int main(){
//master M;
string n;
int c, p, exp;
cout<<"\nName = ";
cin>>n;
cout<<"\nCode = ";
cin>>c;
cout<<"\nPay = ";
cin>>p;
cout<<"\nExperience = ";
cin>>exp;
master M(n,c,p,exp);
M.display();
M.update();
M.display();
return 0;
}

30
OUTPUT

LEARNING AND FINDINGS. Here we learned to create a class network of figure given below. The
class master derives information from both account and admin classes which in turn derive
information from the class person. Define all the four classes and write a program to create,
update and display the information contained in master objects. Also demonstrate the use of
different access specifiers by means of member variables and member functions.

31
EXPERIMENT-12
AIM- Write a C++ program to create three objects for a class named pntr_obj with data members
such as roll_no and name. Create a member function set_data() for setting the data values and
print() member function to print whichobject has invoked it using ‘this’ pointer.
THEORY - Every object in C++ has access to its own address through an important pointer called
this pointer. this pointer is an implicit parameter to allmember functions. Therefore, inside a
member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members ofa class. Only
member functions have a this pointer.
o It can be used to pass current object as a parameter to anothermethod.
o It can be used to refer current class instance variable.
o It can be used to declare indexers.CODE

#include<bits/stdc++.h>
using namespace std;
class prn_obj
{
int rno;
string name;
public:
void set_data(string n, int r)
{
name=n;
rno=r;
}
void print() {
cout<<this->name<<" has invoked print() function"<<endl;
cout<<"The roll number is "<<this->rno<<endl;
}
};
int main()
{
prn_obj ob1,ob2,ob3;
ob1.set_data("Priyanshi",1);
ob2.set_data("Sandali",2);
ob3.set_data("Anjali",3);
ob1.print();
ob2.print();
ob3.print();
return 0;
}

32
OUTPUT

LEARNING AND FINDINGS: By the above experiment we were able to learn and implement concepts of classes and
objects. Class is a feature of object oriented programming through which we are able to solve problems in real
world. Here we made objects of class using objects.

33
EXPERIMENT -13
AIM - Write a C++ program to explain virtual function (polymorphism) by creating a base class
c_polygon which has virtual function area(). Two classesc_rectangle and c_triangle derived from
c_polygon and they have area() to calculate and return the area of rectangle and triangle
respectively.
THEORY –
1. A virtual function is a member function which is declared in
the base class using the keyword virtual and is re-defined (Overriden) bythe derived class.
2. The term Polymorphism means the ability to take many forms. It occursif there is a
hierarchy of classes which are all related to each other
by inheritance.
Consider the following simple program as an example of runtime polymorphism. The main thing to
note about the program is that the derived class’s function is called using a base class pointer. The
idea is that virtual functions are called according to the type of the object instance pointed to or
referenced, not according to the type of the pointer or reference. In other words,virtual functions
are resolved late, at runtime.
CODE
#include<bits/stdc++.h>
using namespace std;
class c_polygon
{
public :
virtual float area() = 0;
};
class c_triangle : public c_polygon
{
float a,b,c;
public :
c_triangle(){}
void setSides(float x , float y , float z)
{
a=x;
b=y;
c=z;

}
float area()
{
float s = (a+b+c)/2;
float ans = sqrt(s*(s-a)*(s-b)*(s-c));

34
return ans;
}

};
class c_rectangle : public c_polygon
{
float l,b;
public :
c_rectangle(){}
void setSides(float x , float y )
{
l=x;
b=y;

}
float area()
{
return l*b;
}

};
int main()
{
cout<<"Enter the sides of the triangle : ";
c_triangle tri;
float a,b,c;
cin>>a>>b>>c;
tri.setSides(a,b,c);
cout<<"Area of the triangle with sides "<<a<<" , "<<b<<" , "<<c<<" =
"<<tri.area()<<endl;
cout<<"Enter the sides of the rectangle : ";
c_rectangle rect;
float l,w;
cin>>l>>w;
rect.setSides(l,w);
cout<<"Area of the rectangle with sides "<<l<<" , "<<w<<" =
"<<rect.area()<<endl;

35
OUTPUT

LEARNING AND FINDINGS: Here we learned to create virtual function (polymorphism) by creating a
base class c_polygon which has virtual function area(). Two classes c_rectangle and c_triangle
derived from c_polygon and they have area() to calculate and return the area of rectangle and
triangle respectively.

36
EXPERIMENT -14
AIM- Write a program to explain class template by creating a template T for a class named pair
having two data members of type T which are inputted by a constructor and a member function get-
max() return the greatest of two numbersto main. Note: the value of T depends upon the data type
specified during objectcreation.
THEORY - C++ adds two new keywords to support
templates: ‘template’ and ‘typename’. The second keyword can always bereplaced by keyword
‘class’.
Templates are expanded at compiler time. This is like macros. The difference is,the compiler does
type checking before template expansion. The idea is simple, source code contains only
function/class, but compiled code may contain multiple copies of same function/class.
Class Templates Like function templates, class templates are useful when a class defines
something that is independent of the data type. Can be useful forclasses like LinkedList,
BinaryTree, Stack, Queue, Array, etc.
CODE
#include <iostream>
using namespace std;
template<class t>
class Pair
{
t a, b;
public:
Pair(t x, t y)
{
a = x;
b = y;
}
t get_max()
{
if(a>b)
return a;
else
return b;
}

};
int main(){ int a,b;
cout<<"Enter the value of two integers : ";
cin>>a>>b;
Pair <int> m(a,b);
cout<<"The max value out of "<<a<<" and "<<b<<" = "<<m.get_max()<<endl;

37
float c, d;
cout<<"Enter the value of two floats : ";
cin>>c>>d;
Pair <float> n(c ,d);
cout<<"The max value out of "<<c<<" and "<<d<<" = "<<n.get_max()<<endl;
return 0;
}
OUTPUT

LEARNING AND FINDINGS: Here we learned to create class template by creating a template T for a
class named pair having two data members of type T which are inputted by a constructor and a
member function get-max() return the greatest of two numbersto main. Note: the value of T depends
upon the data type specified during objectcreation.

38
EXPERIMENT -15
AIM- Write a C++ program to illustrate
i. Division by zero
ii. Array index out of bounds exceptionAlso use
multiple catch blocks.
THEORY - An exception is a problem that arises during the execution of a program. A C++ exception
is a response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception
handling is built upon three keywords: try, catch, and throw.
• throw − A program throws an exception when a problem shows up. This is done using a
throw keyword.
• catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
• try − A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of the
try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code
CODE
i. Division by zero
#include <bits/stdc++.h>
using namespace std;
float CheckDenominator(float den)
{
if (den == 0)
throw "Error";
else
return den;
}
int main()
{
float numerator, denominator, result;
cout<<"Enter the numerator and denominator : ";
cin>>numerator;
cin>>denominator;
try {
if (CheckDenominator(denominator)) {
result = (numerator / denominator);
cout << "The quotient is "

39
<< result << endl;
}
}
catch (...) {
cout << "Exception occurred" << endl;
}
}
ii. Array index out of bounds exception
#include <bits/stdc++.h>
using namespace std;
int main () {
try
{
char * mystring;
mystring = new char [10];
if (mystring == NULL) throw "Allocation failure";
for (int n=0; n<=100; n++)
{
if (n>9) throw n;
mystring[n]='z';
}
}
catch (int i)
{
cout << "Exception: ";
cout << "index " << i << " is out of range" << endl;
}
catch (char * str)
{
cout << "Exception: " << str << endl;
}
return 0;
}
OUTPUT
i. Division by zero

ii. Array index out of bounds exception

40
LEARNING AND FINDINGS: Here we learned to do Division by zero and to create Array index out of bounds
exception and Also used multiple catch blocks.

41

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