Object Oriented Programming - Online Notes
Object Oriented Programming - Online Notes
TABLE OF CONTENTS
COURSE OUTCOME 3
Syllabus 3
UNIT - 1 4
Cout and Cin 4
Function 5
Passing arguments in function 6
Features of Object Oriented Programming 7
Scope Resolution Operator 9
For defining member functions of class outside the class 9
To access the global version of a variable 10
UNIT - 2 11
Constructor 11
Destructor 13
Function Overloading 14
Passing Object as Function Argument 16
Friend Function 18
Inline Function 19
UNIT - 3 21
Inheritance 21
Protected class member 23
Access Specifiers (visibility modes) 24
Ways of inheritance: public, private, protected 24
Pointer to Object 26
Virtual Function 26
UNIT - 4 29
Operator Overloading 29
Overloading Binary Operators Using Friend Function 33
UNIT - 5 34
Template 34
Function Template 34
Types of Errors 35
QUESTION BANK 36
UNIT -1 36
UNIT - 2 37
UNIT - 3 38
UNIT - 4 39
LAB ASSIGNMENT 1 40
Concept based on “Functions” 40
Concept based on “Class & Object” (Pass arguments in functions) 41
Viva Questions based on Lab Assignment 1 41
LAB ASSIGNMENT 2 42
Concept based on “Constructor, Destructor” 42
Concept based on “Function Overloading” 43
Viva Questions based on Lab Assignment 2 43
LAB ASSIGNMENT 3 43
Concept based on “Passing objects as Function Arguments” 44
Viva Questions based on Lab Assignment 3 44
Solution to selected problems of Lab Assignment 3 44
LAB ASSIGNMENT 4 51
Concept based on “Friend Function” 51
Viva Questions based on Lab Assignment 4 52
Solution to selected problems of Lab Assignment 4 52
LAB ASSIGNMENT 5 59
Concept based on “Inheritance and access specifiers (visibility modes)” 59
Concept based on “Pointer to object” 59
Viva Questions based on Lab Assignment 5 59
LAB ASSIGNMENT 6 60
LAB ASSIGNMENT 7 61
Concept based on “Operator Overloading” 61
Concept based on “Overloading Binary Operators using Friend Function” 62
Viva Questions based on Lab Assignment 7 63
Solution to selected problems of Lab Assignment 7 63
LAB ASSIGNMENT 8 64
Concept based on “Template” 64
Concept based on “Exception Handling” 65
Viva Questions based on Lab Assignment 8 65
COURSE OUTCOME
After completion of this course, students will be able to:
CO1: Identify and analyze Object Oriented Programming concepts in designing solution of a problem.
CO2: Apply constructor, friend function and class when analyzing a problem statement.
CO3: Apply and analyze features of inheritance and polymorphism for developing solution of a complex
problem.
CO4: Identify and handle exceptions in an object oriented program. Perform generic programming using
templates.
Syllabus
UNIT-1:
Introduction to different programming paradigm, characteristics of OOP, Class, Object, data
member, member function, structures in C++, different access specifiers, defining member
function inside and outside class, array of objects.
UNIT - 2:
UNIT - 3:
Inheritance, types of inheritance, multiple inheritance, virtual base class, function overriding,
abstract class and pure virtual function
UNIT - 4:
Constant data member and member function, static data member and member function,
polymorphism, operator overloading, dynamic binding and virtual function
UNIT - 5
Exception handling, Template, Stream class, File handling
UNIT - 1
cout in C++, is similar to printf in C. cout is used to display some message on the screen. cout
can be used as:
cout<<”Hello World”;
This statement will display the message “Hello World” on the screen.
cin in C++, is similar to scanf in C. cin is used to take input the value of some variable from the
user. cin can be used as:
cin>>x;
We have to use the header file iostream.h, for cout and cin.
Ques: Write a program in C++ to display a message “Hello World on the screen.
Solution:
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<”Hello World”;
}
Output:
Hello World
Ques: Write a program in C++ to take as input, the value of two integers, from the user. Find
and display the addition of these two integers.
Solution:
void main()
{
int x,y,z;
cin>>x; //Input x
cin>>y; //Input y
z = x + y;
cout<<”Sum = “;
cout<<z;
}
Output:
10
20
Sum = 30
Function
Ques: Write a program in C++ to find the area of rectangle by using a function named as fun().
Solution:
void main()
{
fun(); //calling of function fun
}
void fun()
{
int l,b,area;
cin>>l;
cin>>b;
area = l*b;
cout<<area;
}
Output:
10
20
200
Ques: Write a program in C++ to find the area of rectangle by passing arguments in a function
named as fun(int,int).
Solution:
void main()
{
fun(10,20); //10 and 20 are arguments of function fun
}
void fun(int l,int b)
{
Output:
200
Class is a logical entity while object is a physical entity. Class is like a user defined data type.
Object take up space in memory. For example, the room in which we are sitting is a class and
the objects of this class are black-board, chalk, tables, chairs, fans etc.
A class in C++ has two types of members: data members and function members. (Just like in
the classroom in which we are sitting, there are two types of members: student member and
faculty member). Generally, we put data members in private section of a class and function
members in public section of class.
● Whatever we write under private section of a class, can be accessed only within the
class and not outside the class.
● Whatever we write under public section of a class, can be accessed from both within the
class and outside the class.
2) Encapsulation
The wrapping up of data members and function members together inside a single unit, called as
class is called as encapsulation.
3) Polymorphism
Poly means many and morphism means forms. The ability to take more than one form is called
as polymorphism. There are two types of polymorphism:
4) Data Hiding
The data member of a class should be hidden from outside the class. This can be achieved if
we put data member under private section of a class. This is because whatever we write under
private section can be accessed within the class only and not outside the class.
5) Dynamic Binding
The binding up of the function call with its code at run time is called as dynamic binding.
6) Message Passing
The communication of data from calling function to called function, in the form of arguments
passed to the function, is called as message passing.
7) Data Abstraction
Showing only the data which is required and hiding the unnecessary background details is
called as data abstraction.
8) Inheritance
The ability of one class (called as child class or derived class), to acquire properties from
another class (called as parent class or base class), is called as inheritance. The following are
the types of inheritance:
i) Single inheritance
ii) Multiple inheritance
iii) Multilevel inherirtance
iv) Hierarchical inheritance
v) Hybrid inheritance
void main()
{
abc ob; //ob is object of class abc
ob.fun(); //member function fun of class abc is called using object ob of class abc
}
Output: 10
class abc
{
public:
void fun(); //member function of class abc
void abc::fun() //member function fun of class abc is defined outside class definition
{
cout<<"hello";
}
void main()
{
abc ob;
ob.fun(); //member function fun called
}
Second use of scope resolution operator is to access the global version of a variable (this
cannot be done in C). For example ::count means the global version of the variable count (and
not the local variable count declared in that block)
#include<iostream.h>
#include<conio.h>
int m=10; //global m
void main()
{
clrscr();
int m=20; //m redeclared, local to main
{
int k=m;
int m=30; //m declared again,this time, local to inner block
cout<<"We are in inner block\n";
cout<<"k = "<<k<<"\n";
cout<<"m = "<<m<<"\n";
cout<<"::m = "<<::m<<"\n";
}
cout<<"\nWe are in outer block\n";
cout<<"m = "<<m<<"\n";
cout<<"::m = "<<::m<<"\n";
Output:
We are in inner block
k = 20
m = 30
::m = 10
UNIT - 2
Constructor
A constructor is used to initialize the data member of a class. There are three types of
constructor:
● Default constructor
● Parameterized constructor
● Copy constructor
Example of constructor
class abc
{
private:
int x;
public:
abc() //constructor defined
Output:
10
class abc
{
private:
int x;
public:
abc(int x1)
{
x=x1;
cout<<x;
}
};
void main()
{
abc ob(10);
}
Output: 10
There are two ways of calling a constructor: i) implicit calling of constructor ii) explicit calling of
constructor. In the above program, the statement abc ob(10); is implicit calling of constructor.
This statement can also be written as abc ob = abc(10); This is explicit calling of constructor.
Both implicit and explicit calling of constructor achieves the same effect, but the difference is
that implicit constructor calling is compact than explicit constructor calling.
Destructor
A destructor is used to destroy i.e. free up the memory space occupied by the objects of class.
Properties of Destructor
a) Destructor has the same name as class name, but it is preceded by tilde (~) sign.
b) Destructor releases the memory space occupied by the objects of a class, at the time of
program termination.
c) Destructor is called automatically, at the time of program termination.
Example of destructor
class abc
{
private:
int x;
public:
abc(int x1) //parameterized constructor
{
x = x1;
cout<<x;
}
~abc() // destructor
{
cout<<”\nDestructor called”;
}
};
void main()
{
abc ob(10); //parameterized constructor called- ob’s x will be set to 10
}// destructor called at program termination
Output:
10
Destructor called
Function Overloading
class abc
{
private:
int x,y,s;
void fun(int x1,int y1) //fun defined
{
x = x1; y = y1;
cout<<x*y<<endl;
}
void fun(int s1) //fun redefined - fun is overloaded
{
s = s1;
cout<<s*s;
}
};
void main()
{
abc ob1;
ob1.fun(2,3);
ob1.fun(4);
}
Output:
6
16
When a constructor is defined more than one time such that i) the number of arguments passed
in the constructors differ or ii) the data type of arguments passed in the constructors differ or
both i) and ii) holds true, then this is called as constructor overloading.
class abc
{
private:
int x,y,s;
abc(int x1,int y1) //constructor defined
{
x = x1; y = y1;
cout<<x*y<<endl;
}
abc(int s1) //constructor redefined - constructor is overloaded
{
s = s1;
cout<<s*s;
}
};
void main()
{
abc ob1(2,3);
abc ob2(4);
}
Output:
6
16
We know that in function argument, we can pass variables or constants. Similarly, in function
argument, we can also pass object.
class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
void main()
{
abc ob1,ob2;
ob1.set(1);
ob2.set(2);
ob1.fun(ob2); //ob2 is passed as an argument to function fun
ob1.show();
}
Output: 3
/* Question: Write a program in C++ to copy the price of one fruit object into another. Functions:
set (int), show ( ), copy (fruit) to set the price, show the price and copy the price to another
object.
Solution:*/
#include<iostream.h>
#include<conio.h>
class fruit
{
private:
int price;
public:
void set(int price1)
{
price=price1;
}
void show()
{
cout<<price<<endl;
}
void copy(fruit mango1)
{
price=mango1.price;
}
};
void main()
{
clrscr();
fruit mango,apple;
mango.set(100);
mango.show();
apple.copy(mango); //passing object as function argument
apple.show();
getch();
}
/*Output:
Friend Function
● A function which is not a member function of a class, but can still access the private data
member of a class is called as friend function.
● To declare a function as friend, we precede the function name with the keyword friend.
● Friend function may pass an object as its argument
class abc
{
private:
int x;
public:
friend void fun(); //fun function is now friend function of class abc
};
void fun() /*friend function defined outside class without scope resolution operator (::) -
{
abc ob;
ob.x=10; //friend function accessing private data member x of class abc
cout<<ob.x;
}
void main()
{
fun(); //friend function called (without object and dot operator)
}
Output: 10
Inline Function
When a function gets called, it takes a lot of extra time in executing instructions for tasks like
jumping to the function, saving registers, pushing arguments into the stack and returning to the
calling function. When a function is small, a substantial percentage of execution time may be
spent in such overheads. To eliminate the cost of calls to small functions, C++ proposes a new
feature called as inline function. An inline function is a function that is expanded in line when it is
invoked. That is, the compiler replaces the function call with the corresponding function code
(something similar to macro expansion. But in macros, usual error checking does not occur
during compilation). To make the function as inline, we precede the function name with the
keyword inline, in the function definition. Inline functions must be defined before they are called.
Example:
inline double cube(double a)
{
return (a*a*a);
}
This inline function can be invoked by statements like
c = cube(3.0);
d = cube(2.5+1.5);
On the execution of these statements, the values of c and d will be 27 and 64 respectively.
#include<iostream.h>
#include<conio.h>
inline void fun() //inline function must be defined before it is called
{
int a,b;
cin>>a>>b;
cout<<a+b;
}
Output:
10
20
30
The speed benefits of inline functions diminish as the function grows in size. At some point, the
overhead of the function call becomes small compared to the execution of the function, and the
benefits of inline function may be lost. In such cases, the use of normal functions will be more
meaningful. Usually, when a function is small enough to be defined in one or two lines, then
such a function can be made as inline. The inline keyword merely sends a request, not a
command, to the compiler. The compiler may ignore this request if the function definition is too
long or too complicated and compile the function as a normal function.
Some of the situations where inline expansion may not work are:
Inline expansion makes a program run faster because the overhead of function call and return is
eliminated. However, it makes the program to take up more memory because the statements
that define the inline function are reproduced at each point where the function is called. So, a
trade-off becomes necessary.
UNIT - 3
Inheritance
● The ability of one class, called child class, to acquire properties from another class,
called as parent class is called as inheritance.
● The parent class is also called as base class and child class is also called as derived
class.
● Inheritance is used to achieve reusability of code, which is an important concept of
object oriented programming.
Types of Inheritance
{
public:
void fun()
cout<<“fun”;
};
class b:public a //child class or derived class
{ /* public member function fun of base class a inherited in derived class b, so fun() can be
called with b class object */
};
void main()
{
b ob;
ob.fun(); /*fun of class a called with derived class b’s object, as fun is inherited in b
class*/
}
Output: fun
class a
{
protected:
};
class b : public a
public:
void fun()
{
x=10; /*protected class member x accessed in derived
class b*/
cout<<x;
}
};
void main()
{
b ob;
ob.fun();
}
Output: 10
public → public (i.e public members of base class becomes public members in derived class)
protected → protected (i.e protected members of base class becomes protected members in
derived class)
private → cannot be inherited (i.e private members can NEVER be inherited)
class a : private b { }; //a is derived class and b is parent class i.e. class a is derived from class b
In this case of private inheritance, the following will happen:
public → private (i.e public members of base class becomes private members in derived class)
protected → private (i.e protected members of base class becomes private members in derived
class)
class a : protected b { }; //a is derived class and b is parent class i.e. class a is derived from
class b
In this case of protected inheritance, the following will happen:
public → protected (i.e public members of base class becomes protected members in derived
class)
protected → protected (i.e protected members of base class becomes protected members in
derived class)
Let us summarize the above in the form of a table, for a quick glance and better presentation.
Pointer to Object
A member function of a class can also be called with the help of pointer to object. We use →
(arrow) operator to call the member function of a class, using pointer to object or object pointer.
#include<iostream.h>
#include<conio.h>
class abc
{
public:
void fun()
{
cout<<"a";
}
};
void main()
{
clrscr();
abc *obptr; //obptr is object pointer or pointer to object
obptr->fun(); //fun function called using pointer to object
getch();
}
Output: a
Virtual Function
● A virtual function is a function which is defined in base class and redefined in derived
class. So, virtual function is taking more than one form (polymorphism).
● To declare a function as virtual, we precede the function name (in the base class
version) with the keyword virtual.
● Virtual function is used to achieve Run Time Polymorphism in C++.
public:
virtual void fun()
{
cout<<“a\t“;
}
};
class b:public a
{
public:
void fun()
{
cout<<“b”;
}
};
void main()
{
a *ptr,ob1;
b ob2;
ptr=&ob1;
ptr → fun();
ptr = &ob2;
ptr → fun();
Output: a b
● A pure virtual function is a function which has no body in the base class and that function
is defined in the derived class.
● Syntax to declare pure virtual function:
{
public:
virtual void fun()=0;
};
class b:public a
{
public:
void fun()
{
cout<<“b”;
}
};
void main()
{
a *ptr;
b ob2;
ptr=&ob2;
ptr → fun();
Output: b
UNIT - 4
Operator Overloading
Types of operators
i) Unary operator: is an operator which takes only a single operand. In the statement ++ob,
where ob is an object of some class, then ob is the single operand and unary operator is ++.
ii) Binary operator: is an operator which takes two operands. In the statement ob1 + ob2, where
ob1 and ob2 are objects of some class, then ob1 and ob2 are the operands for the binary
operator +.
● Some operators which cannot be overloaded are: sizeof operator, scope resolution
operator ::, conditional operator ?:, member selection operator . (dot)
class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
void operator ++() /*this is called as overloaded operator function*/
{
x=x+1;
}
};
void main()
{
abc ob1;
ob1.set(10);
ob1.show();
ob1++; /*means ob1.++(); overloaded operator function called */
ob1.show();
}
Output:
10 11
class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
void main()
{
abc ob1,ob2;
ob1.set(1);
ob2.set(2);
ob1+ob2; /*This would mean ob1 . + (ob2); overloaded operator function called */
ob1.show();
}
Output: 3
7c) Create a class distance. Make data members as: feet, inches. Define functions as set (int,
int), show ( ). Make 2 objects of class distance. Set and show the values of data members in set
Solution:
class distance
{
int feet, inch;
public:
void set(int feet1, int inch1)
{
feet = feet1;
inch = inch1;
}
void show()
{
cout<<feet<<”\t”<<inch<<endl;
}
void operator +(distance d) //overloaded operator function defined
{
feet = feet + d.feet;
inch = inch + d.inch;
}
};
void main()
{
clrscr();
distance d1,d2;
d1.set(1,2);
d2.set(3,4);
d1.show();
d2.show();
d1 + d2; //means d1.+(d2);
d1.show();
getch();
}
Output:
1 2
3 4
class abc
{
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
friend abc operator +(int,abc);
};
void main()
Output: 10 12
UNIT - 5
Template
● Template enable us to define generic classes and functions and thus provides support
for generic programming.
● Template is used to achieve reusability of code.
● We can define a single function template, which would be used for addition of two
integers as well as two floats also.
Function Template
The below mentioned program is an example of Function Template.
Explanation: The above program contains a function template, which is used for adding two
numbers (2 integers at one time and two floats at other time). When the function template is
Types of Errors
1) Logic errors
2) Syntactic errors
3) Exceptions
● Logic errors occur due to poor understanding of the problem and solution procedure.
● Syntactic errors occur due to poor understanding of the language itself.
● Run time error is called as an exception.
Exception Handling
● Run time error is called as an exception. C++ has a mechanism to handle exceptions.
The exception handling mechanism of C++ uses the following keywords: try, throw and
catch.
Examples of exception
1) Divide by zero
2) Accessing array out of bound
3) Running out of memory or disk space
Types of Exceptions
● Synchronous exception
● Asynchronous exception
1)The exceptions that are caused by events under the control of the program are called as
synchronous exceptions.
Example: Divide by zero, Accessing array out of bound, Running out of memory or disk space
2) The exceptions that are caused by events beyond the control of the program are called as
The exception handling mechanism in C++ is designed to handle only synchronous exceptions.
void main()
{
int a,b;
cin>>a>>b;
try
{
if(b!=0)
{
cout<<a/b<<"\t";
}
else
{
throw b;
}
}//end of try
catch(int i)
{
cout<<“\tException caught "<<i;
}
}
}//end of main
Output: 12 0 Exception caught 0
QUESTION BANK
UNIT -1
Q2. Explain the concept of structures in C++. Write a program in C++ for structure.
Q3. Justify and prove that a member function of a class can be defined outside the class.
Q5. Prove that Dynamic Binding and Message Passing happens in an object oriented program.
Q9. How local and global variables can be accessed using scope resolution operator?
UNIT - 2
Q1. Define function overloading. Write a program in C++ which supports function overloading.
Q4. What are the various types of constructor? Explain default constructor and parameterized
constructor with the help of programs.
Q5. What is a friend function? Explain the properties of a friend function. Write a program for
friend function.
Q6. What is an inline function? Write a program which supports inline function.
Q9. Is it necessary to always define a constructor in the public section of a class? Justify.
Q10. Comment on the statement: “Generally, we put data and function member of a class under
private and public section, respectively”.
Q11. Can a non-member function of a class access the private data member of a class? If yes,
then explain, how.
Q12. Identify the situations where an inline expansion may not work. What type of functions
should be made as inline? What precautions are required before making a function as inline?
Under what circumstances the benefits of an inline function may diminish? What are the
advantages and disadvantages of making a function as inline?
Q14. Design an object oriented program for justifying compile time polymorphism using function
overloading.
UNIT - 3
Q3. Design an object oriented program utilizing the OOP feature of inheritance. Identify and
justify the type of inheritance.
Q5. How will you justify multilevel inheritance, with the help of a program code?
Q6. What is the advantage of protected class member? Under what circumstances do we need
to use a protected class member?
Q7. Explain the two uses of the visibility modes or access specifiers- public, private and
protected. Compare and distinguish between public, private and protected.
Q9. Explain the concept of virtual function and pure virtual function with an example. What
precautions must be taken while accessing and calling a function that is virtual?
Q11. Use a program code to prove that a virtual function can be used to achieve run time
polymorphism in C++.
UNIT - 4
Q1. What do you mean by operator overloading? What are the rules of operator overloading?
Name the operators which cannot be overloaded.
Q2. Prove that (a+b) != (b+a), where a and b are objects of any class, using operator
overloading.
Q3. Write a program in C++ to overload any unary operator and binary operator.
Q5. Write a program in C++ to add two matrices of size mxn, by overloading the + operator.
Q6. Write a program in C++ to concatenate two strings using operator overloading.
Q7. Can we use a friend function to overload a binary operator? If yes, then justify and explain it
by making a program.
Q9. Suppose A, B and C are objects of the same class, say abc. Perform the following
operations by overloading binary operator using friend function. Overload the overloaded
operator function - in the following manner.
Q2/CO2. What is the advantage of friend function? Write a program in C++ for friend function.
LAB ASSIGNMENT 1
Solve the following problems by programming. Use C++ as the programming language.
1d) Add two numbers using function: don’t pass argument; pass argument.
1e) Find area of rectangle by passing argument to function.
1f) Add two numbers by returning value.
1j) Show that the public members of a class(data and functions) can be accessed both inside
the class and outside the class (i.e in main) but the private members can be accessed inside the
class but NOT outside the class.
1k) Show that a compiler error comes when the member data of a class is initialized at the time
of declaration in a class.
1l) Declare a class fruit. Define 2 functions: setprice( ) & showprice ( ) to set the price and show
the price of fruit respectively. Make an object of class fruit as apple and write the main function.
Make the members of class as: Data- price; Functions: setprice(int) and showprice().
1m) Modify the above program for class distance. Data: feet, inches
1n) Modify the above program for class box. Data: l, b, h for 2 objects.
Q5. Write the syntax to declare, define and call a two argument (first an int, then a float)
function, say f2.
Q6. Write C++ instructions to declare a class c, having private data member m and public
member function f. Declare object o of c. Call f using o.
LAB ASSIGNMENT 2
Solve the following problems by programming. Use C++ as the programming language.
2a) Initialize an integer using default constructor and print its value.
2b) Use parameterized constructors to print the dimensions(length, breadth and height) of two
Box objects using: i) Implicit call ii) Explicit call
2c) Define multiple constructors in a class and hence implement constructor overloading.
2d) Implement destructor.
2g) Display an integer value in a function named f1(int). Display a double value in another
function which has same name as f1(double) using function overloading.
2h) Find the area of rectangle & square using function overloading. (Use different number of
arguments)
LAB ASSIGNMENT 3
Solve the following problems by programming. Use C++ as the programming language.
3b) Copy the price of one fruit object into another. Functions: set (int), show ( ), copy (fruit) to set
the price, show the price and copy the price to another object.
3d) Add the two distances objects d1, d2 (feet, inches) of class distance. Functions: set ( ),
show (), add (distance, distance).
3g) Do question 3d) by passing only one object argument as add (distance).
3h) Write a program to declare a class with two integers. Read values using member functions.
Pass the object to another member function and display the difference between the two
integers.
Q1. How object can be passed as an argument to a function and what is its significance?
/*3a) Implement the following situation: ob1.a = 10, ob2.a = 20. Here ob1 and ob2 are objects of
some class and a is the private data member of the class. Your program should add the data
member of both the objects and assign the result to the private data of ob1. Member functions
of class abc are set(int), show(), add(abc).
Solution:*/
#include<iostream.h>
#include<conio.h>
class abc
{
void show()
{
cout<<a<<endl;
}
void main()
{
clrscr();
abc ob1,ob2;
ob1.set(10);
ob2.set(20);
ob1.show();
ob2.show();
ob1.add(ob2);
/*passing objects as function argument,calling object is ob1*/
ob1.show();
getch();
}
/*Output:
10
20
30*/
#include<iostream.h>
#include<conio.h>
class fruit
{
private:
int price;
public:
void set(int price1)
{
price=price1;
}
void show()
{
cout<<price<<endl;
}
void copy(fruit mango1)
{
price=mango1.price;
}
};
void main()
{
clrscr();
fruit mango,apple;
mango.set(100);
mango.show();
apple.copy(mango); //passing object as function argument
apple.show();
getch();
}
/*Output:
100
100*/
/*3c) Copy the length, breadth, height of one box object of box class into another. Functions:
show ( ), copy (box). Use constructors to initialize the dimensions.
Solution:*/
#include<iostream.h>
#include<conio.h>
class box
{
private:
int l,b,h;
public:
box() //default constructor
{
l = 0;
b = 0;
h = 0;
}
box(int l1,int b1,int h1)
{ //constructor is initializing the dimensions of box object
l=l1;
b=b1;
h=h1;
}
void show()
{
cout<<l<<"\t"<<b<<"\t"<<h<<endl;
}
void copy(box ob)
{
l = ob.l;
b = ob.b;
h = ob.h;
/*LHS l,b,h are of calling object's i.e. ob2's l,b,h */
}
};
void main()
/*Output:
1 2 3
0 0 0
1 2 3*/
/*3d) Add the two distances objects d1, d2 (feet, inches) of class distance. Functions: set ( ),
show (), add (distance, distance).
Solution:*/
#include<iostream.h>
#include<conio.h>
class distance
{
private:
int feet,inches;
public:
void set(int f,int i)
{
feet=f;
inches=i;
}
void show()
{
cout<<feet<<"\t"<<inches<<endl;
}
void add(distance d1,distance d2)
{
void main()
{
clrscr();
distance ob1,ob2,ob3;
ob1.set(1,2);
ob2.set(3,4);
ob1.show();
ob2.show();
ob3.add(ob1,ob2);
ob3.show();
getch();
}
/*Output:
1 2
3 4
4 6*/
#include<iostream.h>
#include<conio.h>
class box
{
private:
int l,b,h;
public:
box() //default constructor
{
void main()
{
clrscr();
box ob1(1,2,3); //parameterized constructor called
box ob2,ob3; //this will expect calling of default constructor
ob1.show();
ob2.show();
ob3 = ob2.copy(ob1); /*copy function is returning an object, so LHS is an object. No
effect on ob2's l,b,h */
ob2.show();
ob3.show();
getch();
}
/*Output:
1 2 3
0 0 0
0 0 0
1 2 3*/
LAB ASSIGNMENT 4
Solve the following problems by programming. Use C++ as the programming language.
4b) Access the private data of a class using friend function by passing object as argument.
4c) Prove that friend function cannot access the private data member directly, but has to use
object name and dot operator to access private data member.
4d) Prove that friend function can be declared either in public or private section of a class.
4e) Create a class abc and find the mean of two numbers using friend function. Member
functions: set (int, int), mean (abc) as a friend function which takes object as argument.
4f) Create a class distance and add two distance objects (feet, inch) using friend function.
4g) Create a class complex to add two complex numbers. Define function add(complex,
complex) as a friend function such that it returns an object of type complex.
4h) Create a class time to add three time objects (hours, min, sec) using friend function. Use
constructors to set the values of all the time objects. You may or may not choose to return the
result object from the friend function. You may also choose the signature of friend function to
take 2 or 3 object arguments, depending on your wish.
/* 4a) Access the private data of a class using friend function without passing object as
argument.
Solution: */
#include<iostream.h>
#include<conio.h>
class abc
private:
public:
};
abc ob;
ob.x = 10; /* friend function accessing private data member x of class abc
cout<<ob.x;
void main()
clrscr();
fun(); //friend function called, without object name and dot operator
getch();
/*Output: 10 */
/* 4b) Access the private data of a class using friend function by passing object as argument.
Solution: */
#include<conio.h>
class abc
private:
int x;
public:
x=x1;
};
cout<<ob1.x;
void main()
clrscr();
ob.set(20);
fun(ob); /*friend function called, passing object as function argument, without object
getch();
/*Output: 20 */
/* 4e) Create a class abc and find the mean of two numbers using friend function. Member
functions: set (int, int), mean (abc) as a friend function which takes object as argument.
Solution: */
#include<iostream.h>
#include<conio.h>
class abc
private:
int x,y;
public:
x=x1;
};
cout<<(ob1.x+ob1.y)/2.0;
void main()
clrscr();
abc ob;
ob.set(3,4);
fun(ob); //friend function called, without object name and dot operator
getch();
/*Output: 3.5 */
/* 4g) Create a class complex to add two complex numbers. Define function add(complex,
complex) as a friend function such that it returns an object of type complex.
#include<iostream.h>
#include<conio.h>
class complex
int real,imag;
public:
real=real1;
imag=imag1;
void show()
cout<<real<<"\t"<<imag<<endl;
friend complex add(complex,complex); /*friend function will take 2 object arguments and
will return an object of class type as complex */
};
complex ob3;
void main()
clrscr();
complex ob1,ob2,ob3;
ob1.set(1,2);
ob2.set(3,4);
ob1.show();
ob2.show();
ob3 = add(ob1,ob2);
ob3.show();
getch();
/* Output:
1 2
3 4
4 6 */
LAB ASSIGNMENT 5
Solve the following problems by programming. Use C++ as the programming language.
5d) Use hierarchical inheritance to derive class b, c and d from class a using public, private and
protected inheritance respectively. What are the differences observed?
5e) Show that a protected class member can be accessed in immediately derived class.
Q3. What is the use of pointer to object? How class member function is called by pointer to
object?
LAB ASSIGNMENT 6
Solve the following problems by programming. Use C++ as the programming language.
Create a class account that stores customer name, account number and type of account. From
this, derive the classes cur_acct and sav_acct to make them more specific to their requirements.
Include necessary member functions in order to achieve the following tasks:
i) Accept deposit from a customer and update the balance.
ii) Display the balance.
iii) Compute and deposit interest.
iv) Permit withdrawal and update the balance.
v) Check for the minimum balance, impose penalty, necessary, and update the
balance.
Do not use any constructors. Use member functions to initialize the class members.
Using these three classes, design a program that will accept dimensions of a triangle or a
rectangle interactively, and display the area. Remember the two values given as input will be
treated as lengths of two sides in the case of rectangles, and as base and height in the case of
triangles.
6c) Extend the above program to display the area of circles. This requires addition of a new
derived class ‘circle’ that computes the area of a circle. Remember, for a circle we need only
one value, its radius, but the get_data( ) function in the base class requires two values to be
passed. (Hint: Make the second argument of get_data( ) function as a default one with zero
value.)
LAB ASSIGNMENT 7
Solve the following problems by programming. Use C++ as the programming language.
7c) Create a class distance. Make data members as: feet, inches. Define functions as set (int,
int), show ( ). Make 2 objects of class distance. Set and show the values of data members in set
7d) Modify the above question 7c) to add two complex numbers.
7e) Add two time objects in the format: hrs, min, sec.
7f) Create a class point and specify x & y co-ordinates. Make two objects of class point pt1 (x1,
y1), pt2 (x2, y2). Your program should make the co-ordinates of pt1 equal to pt2 on specifying
the statement pt2 = pt1 by overloading the binary operator =.
7i) A = B + 5;
7j) A = 5 * B;
7k) A = B + C;
7l) Overload the overloaded operator function - in the following manner. Here abc is the name of
class.
Solution:
class point
{
int x,y;
void set(int x1,int y1)
{
x = x1;
y = y1;
}
void show()
{
cout<<x<<”\t”<<y<<endl;
}
void operator +(point pt) //overloaded operator function
{
x = pt.x;
y = pt.y;
}
};
void main()
{
clrscr();
Output:
1 2
1 2
LAB ASSIGNMENT 8
Solve the following problems by programming. Use C++ as the programming language.
8b) Define a function template to swap two numbers. The numbers being 2 integers at the first
function call and 2 floats when the function is called for the second time.
8c) Define a function template to print an array of 5 numbers. When the function template is
called for the first time, an integer array of size 5 is passed in the function call. When the
function template is called for the second time, a float array of size 5 is passed in the function
call.
8d) There are three function calls for a single function having one argument. An int, a float and a
character is passed during the consecutive function calls. Create a function template to display
the argument passed each time.
8e) A function, having two arguments, is called 3 times. The arguments that are passed are two
integers, two floats and two characters during each consecutive call. Design a function template
to determine the greater among the two arguments for each function call.
8g) Show how an exception can be thrown by a function that is invoked from within a try block.
8h) Show how multiple catch statements are used to handle various types of exceptions.