Вы находитесь на странице: 1из 66

​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE

​Object Oriented Programming

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

Amit Mithal, Department of Computer Science and Engineering Page no: 1 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
Exception Handling 35

QUESTION BANK 36
UNIT -1 36
UNIT - 2 37
UNIT - 3 38
UNIT - 4 39

CO-WISE WEAK STUDENT ASSIGNMENT 39


Weak Student in CO1- Assignment 39
Weak Student in CO2- Assignment 39
Weak Student in CO3- Assignment 40

CO-WISE STRONG STUDENT ASSIGNMENT 40

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

Amit Mithal, Department of Computer Science and Engineering Page no: 2 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
Concept based on “Inheritance” 60
Concept based on “Virtual Function” 60
Concept based on “Pure Virtual Function” 61
Viva Questions based on Lab Assignment 6 61

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:

Amit Mithal, Department of Computer Science and Engineering Page no: 3 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
Concept of reference, dynamic memory allocation using new and delete operators, inline
functions, function overloading, function with default arguments, constructors and destructors,
friend function and classes, using this pointer.

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

C++ is a type of programming language, developed by Bjarne Stroustrup.

Cout and Cin

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;

Amit Mithal, Department of Computer Science and Engineering Page no: 4 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
This statement can be used to take input the value of some variable x from the user. The data
type of x can be int, float, char etc. There is no format specifier %d, %f, %c in cin (although
format specifier was present in scanf).

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

Amit Mithal, Department of Computer Science and Engineering Page no: 5 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
When we classify our program into various functions, then our program becomes more readable
and easier to understand.

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

Passing arguments in function

The advantage of passing arguments or parameters in a function is that there is a


communication of data from calling function to called function.

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)
{

Amit Mithal, Department of Computer Science and Engineering Page no: 6 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
int area;
area = l*b;
cout<<area;
}

Output:
200

Features of Object Oriented Programming

1) Class & Object

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:

Amit Mithal, Department of Computer Science and Engineering Page no: 7 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
● Compile time polymorphism (can be achieved using function overloading and operator
overloading)
● Run time polymorphism (can be achieved using virtual function)

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

Example of class & object

Amit Mithal, Department of Computer Science and Engineering Page no: 8 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
class abc
{
private:
int x; //member data of class abc is x
public:
void fun() //member function of class abc is fun
{
x=10;
cout<<x;
}
}; //class closed

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

Scope Resolution Operator


Scope Resolution Operator, denoted by the symbol :: (double colon) has two uses:
i) For defining member functions of class outside the class
ii) To access the global version of a variable

For defining member functions of class outside the class


We can define member function of a class outside the class definition using scope resolution
operator (denoted as double colon sign ::)

Example of defining member function outside class

class abc
{
public:
void fun(); //member function of class abc

Amit Mithal, Department of Computer Science and Engineering Page no: 9 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
}; // class definition closed

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
}

To access the global version of a variable

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)

Example of :: to access global version of a variable

#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";

Amit Mithal, Department of Computer Science and Engineering Page no: 10 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
getch();
}

Output:
We are in inner block
k = 20
m = 30
::m = 10

We are in outer block


m = 20
::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

● A constructor having zero arguments is called as default constructor.


● A constructor that passes one or more number of arguments is called as parameterized
constructor.

Example of constructor

class abc
{
private:
int x;
public:
abc() //constructor defined

Amit Mithal, Department of Computer Science and Engineering Page no: 11 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
{
x = 10; //private data member initialized
cout<<x;
}
};
void main()
{
abc ob; //constructor called
}

Output:
10

Example of parameterized constructor

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 12 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

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

Amit Mithal, Department of Computer Science and Engineering Page no: 13 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

Function Overloading

● Doing something in excess is called as overloading.


● When a function is defined more than one time such that either the number of arguments
passed in the functions differ or the data type of arguments passed in the functions differ
or both, then this is called function overloading. Function overloading is used to achieve
compile time polymorphism.

Example of 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

Amit Mithal, Department of Computer Science and Engineering Page no: 14 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
Constructor Overloading

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.

Example of 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

Amit Mithal, Department of Computer Science and Engineering Page no: 15 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

Passing Object as Function Argument

We know that in function argument, we can pass variables or constants. Similarly, in function
argument, we can also pass object.

Example of passing object as function argument

class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}

void fun (abc ob)


{ /*object ob is passed as function argument */
x=x+ob.x;
}
};

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

Amit Mithal, Department of Computer Science and Engineering Page no: 16 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

/* 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:

Amit Mithal, Department of Computer Science and Engineering Page no: 17 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
100
100*/

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

Example of Friend Function

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 (::) -

fun is not a member function of class abc*/

{
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)
}

Amit Mithal, Department of Computer Science and Engineering Page no: 18 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

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.

Example of inline function

#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;
}

Amit Mithal, Department of Computer Science and Engineering Page no: 19 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
void main()
{
clrscr();
fun();//inline function called
getch();
}

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:

1. For functions returning values, if a loop, switch or goto exists.


2. For functions not returning values, if a return statement exists.
3. If functions contain static variables.
4. If inline functions are recursive.

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 20 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

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

1) Single inheritance: One class is derived from another class.


2) Multiple inheritance: One class is derived from multiple or more than one classes.
3) Multilevel inheritance: One class is derived from another class, which itself is a derived
class of some other class.
4) Hierarchical inheritance: Multiple classes are derived from a single class.
5) Hybrid inheritance: Combination of any 2 or more than 2 types of inheritance.

Amit Mithal, Department of Computer Science and Engineering Page no: 21 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

Example of single inheritance

class a //base class or parent class

{
public:

void fun()

cout<<“fun”;

};
class b:public a //child class or derived class

Amit Mithal, Department of Computer Science and Engineering Page no: 22 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

{ /* 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

Protected class member


● When a class member is declared to be protected, then the protected class member can
be accessed within the class and in the immediately derived class also.
● The visibility of class member as protected is more than private and less than public.

Example of protected class member

class a

{
protected:

int x; /*protected class member x can be accessed in derived class b*/

};

class b : public a

public:

void fun()

{
x=10; /*protected class member x accessed in derived

Amit Mithal, Department of Computer Science and Engineering Page no: 23 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

class b*/
cout<<x;
}
};
void main()
{
b ob;
ob.fun();
}

Output: 10

Access Specifiers (visibility modes)


Public, private and protected are called as visibility modes or access specifiers.
Public, private and protected have 2 uses:

a) As class members (already discussed)

b) As a way to derive one class from another

Ways of inheritance: public, private, protected


a) Deriving one class from another, using public visibility mode
class a : public b { }; // a is derived class and b is parent class i.e. class a is derived from class b

In this case of public inheritance, the following will happen:

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)

b) ​Deriving one class from another, using private visibility mode

Amit Mithal, Department of Computer Science and Engineering Page no: 24 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

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)

private → cannot be inherited (i.e private members can NEVER be inherited)

c) ​Deriving one class from another, using protected visibility mode

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)

private → cannot be inherited (i.e private members can NEVER be inherited)


Note that, after inheritance, the visibility of class members (which are inherited) either remains
as it is or visibility decreases and visibility will NEVER INCREASE, in any case.

Let us summarize the above in the form of a table, for a quick glance and better presentation.

Way of inheritance → private protected public


Base class members ↓

private can never be can never be can never be


inherited in derived inherited in derived inherited in derived
class class class

protected becomes ​private remains ​protected​ in remains ​protected​ in


in derived class, derived class, after derived class, after
after inheritance inheritance inheritance

public becomes ​private remains ​protected​ in remains ​public​ in


in derived class, derived class, after derived class, after
after inheritance inheritance inheritance

Amit Mithal, Department of Computer Science and Engineering Page no: 25 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

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.

Example of pointer to object

#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++.

Amit Mithal, Department of Computer Science and Engineering Page no: 26 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
● Virtual function is called with the help of pointer to object of base class. It depends on
the contents of pointer to object of base class, as to which version of virtual function will
be called- either of base class or of derived class. If pointer to object of base class
contains address of base class object and then virtual function is called, then virtual
function of base class will be called. Secondly, if pointer to object of base class contains
address of derived class object and then virtual function is called, then virtual function of
derived class will be called. The contents of pointer to object is checked at run time, so
we say that virtual function is used to achieve Run Time Polymorphism in C++. Virtual
function is called with the help of pointer to object of base class and using → (arrow)
operator. This concept is illustrated in the following example:

Example of Virtual Function


class a

public:
virtual void fun()
{
cout<<“a\t“;
}
};
class b:public a
{
public:
void fun()
{
cout<<“b”;
}
};

void main()

{
a *ptr,ob1;

Amit Mithal, Department of Computer Science and Engineering Page no: 27 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

b ob2;

ptr=&ob1;

ptr → fun();

ptr = &ob2;

ptr → fun();

Output: a b

Pure virtual function

● 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:

virtual void base_class_function() = 0; (in base class definition)

Example of pure virtual function


class a

{
public:
virtual void fun()=0;
};
class b:public a
{
public:
void fun()
{
cout<<“b”;
}
};

void main()

Amit Mithal, Department of Computer Science and Engineering Page no: 28 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

{
a *ptr;

b ob2;

ptr=&ob2;

ptr → fun();

Output: b

UNIT - 4
Operator Overloading

● Doing something in excess is called as overloading.


● When an operator is used to operate on objects, in addition to constants and variables,
then this is called as 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)

● Syntax of unary operator overloading:


return_type_of_function operator operator_to_be_overloaded(no object argument);

Amit Mithal, Department of Computer Science and Engineering Page no: 29 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

● Syntax of binary operator overloading:


return_type_of_function operator operator_to_be_overloaded(one object argument);

Example of unary operator overloading

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

Amit Mithal, Department of Computer Science and Engineering Page no: 30 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

Example of binary operator overloading

class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}

void show()
{
cout<<x<<“\t”;
}

void operator +(abc ob)


{ /*overloaded operator function defined*/
x = x + ob.x; /*This would mean ob1’s x = ob1’s x + ob2’s x */
}
};

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

Amit Mithal, Department of Computer Science and Engineering Page no: 31 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
(int, int) and show ( ) functions respectively. Now overload the binary operator + to add these 2
objects using the concept of operator overloading.

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

Amit Mithal, Department of Computer Science and Engineering Page no: 32 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
4 6

Overloading Binary Operators Using Friend Function


● Friend functions may be used in place of member functions for overloading a binary
operator, the only difference being that a friend function requires two arguments to be
passed, while a member function requires only one. The statement ob3 = ob1 + ob2;
(where ob1, ob2, ob3 are objects of the same class) is equivalent to ob3 = operator
+(ob1,ob2);
● For overloading using statements like ob1 = 2 + ob2; a member function will not work,
but a friend function will work.

Example to overload binary operator using friend function

class abc
{
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
friend abc operator +(int,abc);
};

abc operator +(int a,abc ob)


{
abc ob3;
ob3.x = a + ob.x;
return ob3;
}

void main()

Amit Mithal, Department of Computer Science and Engineering Page no: 33 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
{
abc ob1,ob2;
ob1.set(10);
ob1.show();
ob2 = 2 + ob1; /*equivalent to ob2 = operator +(2,ob1); */
ob2.show();
}

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.

template <class t>


void fun(t a,t b) /* this is function template. t can be any data type */
{
cout<<a+b<<“\t”;
}
void main()
{
fun(1,2); // function template called, for 2 integers
fun(1.1,2.1); //// function template called, for 2 floats
}
Output: 3 3.2

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

Amit Mithal, Department of Computer Science and Engineering Page no: 34 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
called for the first time, it will add two integers. When the function template is called for the
second time, it will add two float numbers.

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

asynchronous exceptions. Example: Keyboard Interrupts.

The exception handling mechanism in C++ is designed to handle only synchronous exceptions.

Amit Mithal, Department of Computer Science and Engineering Page no: 35 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
Example of Exception Handling

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

Q1. Explain the characteristics of Object Oriented Programming.

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 36 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
Q4. Prove that a member function can access the private data of the class.

Q4. Explain the various programming paradigms.

Q5. Prove that Dynamic Binding and Message Passing happens in an object oriented program.

Q6. Identify the various OOP features in an object oriented program.

Q7. Justify the concept of Encapsulation, by defining a class.

Q8. How Data Hiding is provided in an object oriented program? Justify.

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.

Q2. Explain constructor and destructor with an example.

Q3. Write the properties of constructor and destructor.

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.

Q7. Analyze the concept of Function Overloading in a C++ program.

Q8. Compare the various types of function overloading.

Q9. Is it necessary to always define a constructor in the public section of a class? Justify.

Amit Mithal, Department of Computer Science and Engineering Page no: 37 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

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?

Q13. How can the address of a variable be passed as a function argument?

Q14. Design an object oriented program for justifying compile time polymorphism using function
overloading.

UNIT - 3

Q1. What is inheritance? What is the advantage of inheritance?

Q2. Compare and Analyze the various types of inheritance.

Q3. Design an object oriented program utilizing the OOP feature of inheritance. Identify and
justify the type of inheritance.

Q4. Prove multiple inheritance, programmatically.

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 38 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
Q8. What is pointer to object? How a member function of a class can be called using pointer to
object?

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?

Q10. Under what circumstances do we need to use pure virtual function?

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.

Q4. Justify compile time polymorphism using operator overloading, programmatically.

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.

Q8. Perform function overloading in operator overloading (overloaded operator function) by


writing a program to solve the following problem:

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.

friend abc operator-(int,abc); // A = 5 * B;

Amit Mithal, Department of Computer Science and Engineering Page no: 39 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

friend abc operator-(abc,int); // A = B + 5;

friend abc operator-(abc,abc); // A = B + C;

CO-WISE WEAK STUDENT ASSIGNMENT


Weak Student in CO1- Assignment
Q1/CO1. Explain the features of Object Oriented Programming.
Q2/CO1. Design an object oriented program to explain how the concept of Data Hiding is
achieved in C++.

Weak Student in CO2- Assignment


Q1/CO2. Explain the concept of function overloading with an example.

Q2/CO2. What is the advantage of friend function? Write a program in C++ for friend function.

Weak Student in CO3- Assignment


Q1/CO3. Draw figures for various types of inheritance and define the types of inheritance.
Q2/CO3. What do you mean by virtual function? Design an object oriented program in C++ to
illustrate the concept of pure virtual function.

Amit Mithal, Department of Computer Science and Engineering Page no: 40 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

CO-WISE STRONG STUDENT ASSIGNMENT


GATE 2005/CO1: Which of the following are essential features of an object-oriented
programming languages?
1. Abstraction and encapsulation
2. Strictly-typedness
3. Type-safe property coupled with sub-type rule
4. Polymorphism in the presence of inheritance
(A) 1 and 2 only (B) 1 and 4 only (C) 1, 2 and 4 only (D) 1, 3 and 4 only

LAB ASSIGNMENT 1
Solve the following problems by programming. Use C++ as the programming language.

Concept based on “cout, cin”

1a) Print a message.


1b) Add three integers without taking input from the user.
1c) Add three integers taking input from user.

Concept based on “Functions”

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.

Concept based on “Class & Object” ​(Pass arguments in


functions)

1g) Print a message


1h) Find area of rectangle.

Amit Mithal, Department of Computer Science and Engineering Page no: 41 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
1i) Find area of square.

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.

Viva Questions based on Lab Assignment 1

Q1. What is the use of cout and cin?


Q2. Write one instruction in C++ to print the value of a float variable, say v1.
Q3. Write one instruction in C++ to input the value of an integer, say v2.
Q4. Write the syntax to declare, define and call a zero argument function, say f1.

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 42 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

LAB ASSIGNMENT 2

Solve the following problems by programming. Use C++ as the programming language.

Concept based on “Constructor, Destructor”

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.

Concept based on “Function Overloading”

Amit Mithal, Department of Computer Science and Engineering Page no: 43 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
2e) Use function overloading using different number of arguments to add some integers.
2f) Use function overloading to add 2 integers & 2 double numbers.

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)

Viva Questions based on Lab Assignment 2

Q1. Name and explain the features of object oriented programming.


Q1. What is constructor?
Q2. What are the properties of constructor?
Q3. What is destructor?
Q4. What are the properties of destructor?
Q5. Explain default constructor and parameterized constructor.
Q6. What is constructor overloading and function overloading?
Q7. What is polymorphism? How compile time polymorphism is achieved in C++ (using function
overloading)?

LAB ASSIGNMENT 3
Solve the following problems by programming. Use C++ as the programming language.

Concept based on “Passing objects as Function Arguments”


3a) Implement the following situation: ob1.a = 10, ob2.a = 20. Here ob1 and ob2 are objects of
some class abc 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).

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 44 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
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.

3d) Add the two distances objects d1, d2 (feet, inches) of class distance. Functions: set ( ),
show (), add (distance, distance).

3e) Do question 3c) by returning object from copy (box) function.

3f) Do question 3d) by returning object from 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.

Viva Questions based on Lab Assignment 3

Q1. How object can be passed as an argument to a function and what is its significance?

Solution to selected problems of Lab Assignment 3

Concept based on “Passing objects as Function Arguments”

/*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
{

Amit Mithal, Department of Computer Science and Engineering Page no: 45 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
private:
int a;
public:
void set(int a1)
{
a=a1;
}

void show()
{
cout<<a<<endl;
}

void add(abc ob3) //passing objects as function argument


{
a=a+ob3.a;
/*calling object ob1's a = calling object ob1's a + ob2's a*/
}
};

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*/

Amit Mithal, Department of Computer Science and Engineering Page no: 46 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
/*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.
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:
100
100*/

Amit Mithal, Department of Computer Science and Engineering Page no: 47 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

/*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()

Amit Mithal, Department of Computer Science and Engineering Page no: 48 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
{
clrscr();
box ob1(1,2,3); //parameterized constructor called
box ob2; //this will expect calling of default constructor
ob1.show();
ob2.show();
ob2.copy(ob1);
ob2.show();
getch();
}

/*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)
{

Amit Mithal, Department of Computer Science and Engineering Page no: 49 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
feet = d1.feet + d2.feet;
inches = d1.inches + d2.inches;
/*LHS feet and inches is of that object who is calling this add function*/
}
};

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*/

/*3e) Do question 3c) by returning object from copy (box) function.


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: funarg5.cpp*/

#include<iostream.h>
#include<conio.h>

class box
{
private:
int l,b,h;
public:
box() //default constructor
{

Amit Mithal, Department of Computer Science and Engineering Page no: 50 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
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;
}
box copy(box ob) /*return type of copy function is class, as this function is returning
object of class box*/
{
box ob3;
ob3.l = ob.l;
ob3.b = ob.b;
ob3.h = ob.h;
/*LHS l,b,h are of calling object's i.e. ob3's l,b,h */
return ob3; //object is returned
}
};

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();
}

Amit Mithal, Department of Computer Science and Engineering Page no: 51 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

/*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.

Concept based on “Friend Function”


4a) Access the private data of a class using friend function without passing object as argument.

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 52 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

Viva Questions based on Lab Assignment 4

Q1. What is a friend function?


Q2. What are the properties of friend function?

Solution to selected problems of Lab Assignment 4


Concept based on “Friend Function”

/* 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:

Amit Mithal, Department of Computer Science and Engineering Page no: 53 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
int x;

public:

friend void fun(); //friend function declared; non-member function

};

void fun() //friend function defined, without :: operator

abc ob;

ob.x = 10; /* friend function accessing private data member x of class abc

Must use object to access data member*/

// x=10; will give error- undefined symbol x

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: */

Amit Mithal, Department of Computer Science and Engineering Page no: 54 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
#include<iostream.h>

#include<conio.h>

class abc

private:

int x;

public:

void set(int x1)

x=x1;

friend void fun(abc); //friend function declared; non-member function

};

void fun(abc ob1) //friend function defined, without :: operator

cout<<ob1.x;

/* friend function accessing private data member x of class abc

Must use object to access data member*/

void main()

clrscr();

Amit Mithal, Department of Computer Science and Engineering Page no: 55 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
abc ob;

ob.set(20);

fun(ob); /*friend function called, passing object as function argument, without object

name and dot operator */

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:

void set(int x1,int y1)

x=x1;

Amit Mithal, Department of Computer Science and Engineering Page no: 56 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
y=y1;

friend void fun(abc); //friend function declared; non-member function

};

void fun(abc ob1) //friend function defined, without :: operator

cout<<(ob1.x+ob1.y)/2.0;

/* friend function accessing private data member x and y of class abc

Must use object to access data member*/

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 57 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
Solution: */

#include<iostream.h>

#include<conio.h>

class complex

int real,imag;

public:

void set(int real1,int imag1)

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 add(complex ob1,complex ob2)

complex ob3;

Amit Mithal, Department of Computer Science and Engineering Page no: 58 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
ob3.real = ob1.real + ob2.real;

ob3.imag = ob1.imag + ob2.imag;

return ob3; //object is returning from function add

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 */

Amit Mithal, Department of Computer Science and Engineering Page no: 59 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

LAB ASSIGNMENT 5
Solve the following problems by programming. Use C++ as the programming language.

Concept based on “Inheritance and access specifiers (visibility


modes)”
5a) Create a class ‘a’. Define a member function fun of class a to print the message “hello”.
Derive a class ‘b’ from class a. Inside main function, use the object of class b to call the member
function fun of class a and hence prove single inheritance.

5b) Prove multiple inheritance.

5c) Justify multilevel inheritance.

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.

Concept based on “Pointer to object”

5f) Call the member function of a class using pointer to object.

Viva Questions based on Lab Assignment 5

Q1. Define inheritance and types of inheritance.


Q2. Differentiate between public, private and protected as i) class members ii) way to derive one
class from another.

Q3. What is the use of pointer to object? How class member function is called by pointer to
object?

Amit Mithal, Department of Computer Science and Engineering Page no: 60 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

LAB ASSIGNMENT 6
Solve the following problems by programming. Use C++ as the programming language.

Concept based on “Inheritance”


6a) Assume that a bank maintains two kinds of accounts for customers, one called as savings
account and the other as current account. The savings account provides compound interest and
withdrawal facilities but no cheque book facility. The current account provides cheque book
facility but no interest. Current account holders should also maintain a minimum balance and if
the balance falls below this level, a service charge is imposed.

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.

Concept based on “Virtual Function”


6b) Create a base class called shape. Use this class to store two double type values that could
be used to compute the area of figures. Derive two specific classes called triangle and rectangle
from the base class shape. Add to the base class, a member function get_data( ) to initialize
base class data members and another member function display_area( ) to compute and display
the area of figures. Make display area( ) as a virtual function and redefine this function in the
derived classes to suit their requirements.

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 61 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

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.)

Concept based on “Pure Virtual Function”


6d) Run the above program with the following modifications:
i) Remove the definition of display_area( ) from one of the derived classes.
ii) In addition to the above change, declare the display_area( ) as virtual in the base
class shape.

Comment on the output in each case.

Viva Questions based on Lab Assignment 6

Q1. What do you mean by virtual function?


Q2. What do you mean by pure virtual function?

LAB ASSIGNMENT 7
Solve the following problems by programming. Use C++ as the programming language.

Concept based on “Operator Overloading”


7a) Overload unary operator ++.

7b) Overload unary operator --.

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

Amit Mithal, Department of Computer Science and Engineering Page no: 62 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
(int, int) and show ( ) functions respectively. Now overload the binary operator + to add these 2
objects using the concept of operator overloading.

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 =.

7g) Overload + operator to add two matrices of size m*n.

7h) Concatenate 2 strings.

Concept based on “Overloading Binary Operators using Friend


Function”
Suppose A, B and C are objects of the same class. Perform the following operations by
overloading binary operator using friend function:

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.

friend abc operator-(int,abc);

friend abc operator-(abc,int);

friend abc operator-(abc,abc);

Amit Mithal, Department of Computer Science and Engineering Page no: 63 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

Viva Questions based on Lab Assignment 7


Q1. Define operator overloading.
Q2. What are the rules for operator overloading?
Q3. What are the operators which cannot be overloaded.
Q4. What do you mean by unary, binary and ternary operators and give their examples.
Q5. What is the syntax of unary and binary operator overloading?
Q6. Which feature of C++ does operator overloading supports and how?
Q7. How friend function can be used to overload binary operators?

Solution to selected problems of Lab Assignment 7


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 =.

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();

Amit Mithal, Department of Computer Science and Engineering Page no: 64 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming
point pt1,pt2;
pt1.set(1,2);
pt1.show();
pt2 = pt1; //means pt2.=(pt1); This will call overloaded operator function
pt2.show();
getch();
}

Output:
1 2
1 2

LAB ASSIGNMENT 8
Solve the following problems by programming. Use C++ as the programming language.

Concept based on “Template”


8a) Define a function template to add two numbers. The numbers being 2 integers at the first
function call and 2 floats when the function is called for the second time.

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.

Amit Mithal, Department of Computer Science and Engineering Page no: 65 of 66


​ ​JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
​Object Oriented Programming

Concept based on “Exception Handling”


8f) Handle the exception “divide by zero” using try, throw, catch keywords of exception handling
mechanism.

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.

8i) Catch and handle various types of exceptions using catch(…)

8j) Show how an exception can be rethrown and caught.

Viva Questions based on Lab Assignment 8


Q1. What is template, function template and what are their advantages?
Q2. Name and explain the various types of errors.
Q3. Name and explain the various types of exceptions.
Q3. How various types of exceptions can be caught and handled?
Q4. How an exception can be rethrown and caught?

Amit Mithal, Department of Computer Science and Engineering Page no: 66 of 66

Вам также может понравиться