0% found this document useful (0 votes)
19 views32 pages

OOP Material Unit 1 2 3

Bca question with solutions

Uploaded by

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

OOP Material Unit 1 2 3

Bca question with solutions

Uploaded by

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

Object Oriented Programming

Difference between Procedures Oriented Programming (POP) and Object Oriented


Programming.(OOP)

POP(C) OOP(C++)

In POP, importance is given to the In OOP, importance is given to the data.


sequence of things to be done i.e.
algorithms

In POP, larger programs are divided into In OOP, larger programs are divided into
functions objects.

In POP, most functions share global data In OOP mostly the data is private and only
i.e data move freely around the system functions inside the object can access the
from function to function. data.

POP follows a top down approach in OOP follows a bottom up approach.


problem solving

In POP, adding of data and function is In OOP it is easy.


difficult.

In POP, there are no access specifiers. In OOP there are public, private and
protected specifiers.

In POP, operator cannot be overloaded In OOP operator can be overloaded.

A function transforms data from one from Objects may communicate with each other
to another. through functions

Data is not hidden easily to access. Data is hidden and can’t access by other
function

POP has no facility like class, abstraction, OOP has facility like class, abstraction,
inheritance, encapsulation, inheritance, encapsulation,
polymorphism..etc polymorphism..etc

Eg ..C, QBASIC, PASCAL are procedure Eg.. C++, JAVA are Object Oriented
oriented language. Language.
Object Oriented Programming
Explain Characteristics of OOP.
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data and functions are tied together in the data structure.
4. Data is hidden and can not be accessed by external functions.
5. Objects may communicate with each other through functions.
6. New data and functions can be easily added whenever necessary.
7. Bottom-up approach.

Explain Enum with an example.


Enumerated type (enumeration) is a user-defined data type which can be assigned some
limited values. These values are defined by the programmer at the time of declaring the
enumerated type.
For example: If a gender variable is created with value male or female. If any other value
is assigned other than male or female then it is not appropriate. In this situation, one can
declare the enumerated type in which only male and female values are assigned.
Syntax:
enum enumerated-type-name{value1, value2, value3…..valueN};
enum keyword is used to declare enumerated types after that enumerated type name
was written then under curly brackets possible values are defined.
1. It can be declared during declaring enumerated types, just add the name of the
variable before the semicolon. or,
2. Beside this, we can create enumerated type variables as same as the normal
variables.
Example
int main()
{
// Defining enum Gender
enum Gender { Male, Female };

// Creating Gender type variable


Gender gender = Male;

switch (gender)
{
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
cout << "Value can be Male or Female";
}
return 0;
}
Object Oriented Programming

Output:
Gender is Male

Example
enum year {
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec
};

// Driver Code
int main()
{
int i;

// Traversing the year enum


for (i = Jan; i <= Dec; i++)
cout << i << " ";

return 0;
}

What is Class, Objects? Explain with example.


Class:- Objects are variable of class type. Once a class is defined, we can create any
number of objects belonging to that class. Classes are user-defined data types and behave
like built-in types of programming languages.

Objects: - Objects are basic run-time entities. They contain data and code together. They
may represent a person, a place, a bank account, a table of data, or any item in the
program. Program objects should be chosen such that they match closely with the real
world. Objects take up space in memory. Objects can communicate with one another by
sending messages.
Object Oriented Programming
Example:-
#include <iostream.h>
#include <conio.h>
class test //Class name
{
int data;
public:
void read() //method
{
cout<<"Enter any no:=>";
cin>>data;
}
void show() //method
{
cout<<data<<endl;
}
};
void main()
{
clrscr();
test t; //define object for accessing a class.
t.read();
t.show();
getch();
}
What is visibility modifier OR access specifiers? List out differentiate with proper
example
To provide the facility of security by means of data hiding, is get done by some access
specifies and these access specifies are known as visibility modifiers or access
specifiers.
These visibility modifiers are used to secure the data member and member function of
a class.
There are threes types of visibility modifiers 1. Public 2. Private 3. Protected
Public variables are variables that are visible to all classes.
Private variables are variables that are visible only to the class to which they belong.
Protected variables are variables that are visible only to the class to which they belong,
and any subclasses
Deciding when to use private, protected or public variable is sometimes tricky. You
need to think whether or not an external object (or program), actually needs direct access
to the information. If you do want other objects to access internal data, but wish to
control it, you would make it either private or protected, but provide functions which can
manipulate the data in a controlled way.
Object Oriented Programming
What are the different between class and structure?
Class Structure
A class is way to bind the data and its A structure is a user defined data type
associated functions together. And it allows which is the collection of different of
the data to be hidden from external use. elements who having different Data types.
A class has three access modifiers. A structure has not any access modifier.
Public, Private, Protected
Class keyword is used to declare the class Struct keyword is used declare the
structure.
Class binds both data and member Structure contain only data.
functions.
Syntax: Syntax:
Class <class name> Struct <structure name>
{ {
Private: data type variable1;
Public: data type variable2;
Protected: data type variable2;
}; };

What is encapsulation or what is data hiding? How it is implemented in C++?


The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the class
can access it.
In general, encapsulation is the inclusion of one thing within another thing so that the
included thing is not apparent. Decapsulation is the removal or the making apparent a
thing previously encapsulated.
In OOP, encapsulation is the inclusion within a program object of all resources need
for the object to function – basically, the methods and the data. The object is said to
publish its interfaces. Other objects add here to these interfaces to use the object without
having to be concerned with how the object accomplishes it.
An object can be through of as a self –contained atom. The object interface consists of
public methods and instantiated data.
Example
#include <iostream.h>
#include <conio.h>
class Square
{
private:
int Num;

public:
void Get()
{
cout<<"Enter Number:";
cin>>Num;
Object Oriented Programming
}
void Display()
{
cout<<"Square Is:"<<Num*Num;
}
};

void main()
{
Square Obj;
Obj.Get();
Obj.Display();
getch();
}
Explain scope resolution operator with example.
In C, the global version of a variable cannot be accesses from within the inner block.
C++ resolves this problem by introducing a new operator :: called the scope resolution
operator. This can be used uncover a hidden variable.

Syntax ::variable name


Example:-
#include <iostream.h>
#include <conio.h>
int m= 10;//global m
main()
{
int m=20; //m redeclared, local to main
clrscr();
{
int k=m;
int m=30; //m declared again local to inner block
cout<<"we are inner block \n";
cout<<"k= "<< k << "\n";
cout<<"m= "<< m << "\n";
cout<<"::m=" <<::m << "\n";
}
cout<<"we are outer block \n";
cout<<"m= "<< m << "\n";
cout<<"::m=" <<::m << "\n";
}
Note:- It is to be noted ::m will always refer to the global m
Object Oriented Programming
What is constructor? List out the characteristics of it. Explain with example.
A constructor is a ‘special’ member function whose task is to initialize the objects of
its class. It is special because its name is the same as the class name. constructor is
involved is declared and defined as follow:
Example:
class integer
{
int m,n;
public:
integer()//declaring the constructor
{
m=25;n=96;
cout<<m<<endl<<n;
}
};
main()
{
clrscr();
integer i1;
getch();
}
Characteristics:-
They should be declared in the public section.
They are invoked automatically when the objects are created.
They do not have return types.
They can not be inherited, though a derived class can call the base constructor.
They have default arguments.
Constructor can not be virtual.
We can not refer to their address.

What is parameterized constructor? How constructor called explicitly/implicitly?


C++ permits us to achieve these objectives by passing arguments to the constructor
function when the objects are created. The constructors that can take arguments are called
parameterized constructor.
We must pass the initial values as arguments to the constructor function when an
object is declared. This can be done in two ways:
1. By calling the constructor explicitly.
2. By calling the constructor implicitly.
Example
#include <iostream.h>
#include <conio.h>
class para_cons
{
int m,n;
public:
para_cons(int,int); //constructor declared
Object Oriented Programming
void display()
{
cout<<"m ="<< m << "\n";
cout<<"n ="<< n << "\n";
}
};
para_cons::para_cons(int x, int y) //constructor defined
{
m=x; n=y;
}
main()
{
clrscr();
para_cons obj1(10,20); //constructor called implicitly
para_cons obj2=para_cons(100,200); //constructor called explicitly
cout << "\n OBJECT 1" << "\n";
obj1.display();
cout << "\n OBJECT 2" << "\n";
obj2.display();
getch();
}

Explain constructor with default argument?


It is possible to define constructor with default arguments. In following example
complex (float r, float i=0) The default value of the argument i is Zero. Then , the
statement complex obj1(10.51) assigns the value 10.51 to r variable and 0.0 to i
Example
class complex
{
float real,imag;
public:
complex(float r,float i=0)//constructor declared
{
real=r;
imag=i;

}
void display()
{

cout<<"Real=>"<< real << "\n";


cout<<"Imag=>"<< imag << "\n";
}
};
void main()
{
Object Oriented Programming
clrscr();
complex obj1(10.51); //constructor called implicitly
cout << "\n OBJECT 1" << "\n";
obj1.display();
getch();
}
What is constructor? When copy constructor is called? What is an advantage of
using copy constructor?
A constructor is a ‘special’ member function whose task is to initialize the objects of
its class. It is special because its name is the same as the class name.
Copy constructor is used to declare and initialize an object from another object.For
example, the statement code B (A);
Would define the object B and at the same time initialize it to the value of A.
Another from of statement is code B = A;
The process of initializing through a copy constructor is known as copy initialization.
Remember the statement B=A; will not invoke the copy constructor. However, if B
and A are objects, this statement is legal and simply assign the values A to B, member by
member. This is the task of the overloaded assignment operator (=).
A copy constructor takes a reference to an object of the same class as itself as an
argument. Let us consider a simple example of constructing and using a copy constructor
as shown in program.
Example
class copy_cons
{
int id;
public:
copy_cons(){};//constructor declared
copy_cons(int a) //constructor again
{
id=a;
}
copy_cons(copy_cons & x)//copy constructor
{
id=x.id;
}
void display()
{
cout<<id;
}
};
void main()
{
clrscr();
copy_cons A(100); //Object A is created and initialize
copy_cons B(A); //Copy constructor called
copy_cons C=A;//Copy constructor called again
Object Oriented Programming
copy_cons D; //D is created, not initialized
D=A; //Copy constructor not called
cout <<"\n id of A:=>";A.display();
cout <<"\n id of B:=>";B.display();
cout <<"\n id of C:=>";C.display();
cout <<"\n id of D:=>";D.display();
getch();
}
Advantages
A reference variable has been use an argument of the copy constructor. We can not
pass the argument by value to a copy constructor.
When no copy constructor is defined the compiler supplies its own copy constructor.

Write major differences between constructor and destructor.


Constructor Destructor
1. Its name is same as class name. 1. Its name is same as class name preceded
by ~ (tilde).
2. It is called automatically when an object 2. It is called automatically when an object
is created. is destroyed.
3. It can have any number of arguments. 3. It never takes any argument.
4. Normally new is used in constructor to 4. Normally ‘delete’ is used in destructor to
allocate memory to objects. free memory from objects.

What is friend function? Why we need to write friend function? Explain with
example. Discuss its advantages.
We know that the private members can not be accessed from outside the class. That is,
a non member function cannot have an access to the private data of a class.
For example, consider a case where two classes, manager and scientist, have been
defined. We would like to use a function income_tax ( ) to operate on the object of both
classes. In the situations, C++ allows the common function to be made friendly with both
classes, there by allowing the function to have access to the private data of these classes.
Syntax
Class Abc
{
Public:
………….
………….
friend void xyz(void); //declaration
};
The function declaration should be preceded by the keyword friend.
Characteristics of friend function
It is not in the scope of the class to which it has been declared as friend.
Object Oriented Programming
Since it is not in the scope of the class, it can not be called using the object of that
class.
It can be invoked like a normal function without the help of any object.
Unlike member function, it can not access the member names directly and has to use
an object name and not membership operator with each member name(eg. A.x).
It can be declared either in the public or the private part of a class without affecting its
meaning.
Usually, it has the objects as arguments.
The friend functions are often used in operator overloading.
Example (Data members are private)
#include <iostream.h>
#include <conio.h>
class sample
{
private:
int a;
int b;
public:
void setvalue()
{
a=25;b=40;
}
friend float mean(sample s);
};
float mean (sample s)
{
return float(s.a + s.b)/2.0;
}
void main()
{
clrscr();
sample x;
x.setvalue();
cout << "Mean Value:=> " << mean(x)<<"\n";
getch();
}
A simple example of a friend class.
class A
{
int x =5;
Object Oriented Programming
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;
B b;
b.display(a);
return 0;
}
Object Oriented Programming
What is Inheritance? Explain Types of Inheritance with example.

The mechanism of deriving a new class from an old one is called inheritance (or
derivation).The old class is referred to as the base class and the new one is called the
derived class or subclass.

Inheritance is a mechanism of reusing and extending existing classes without


modifying them, thus producing hierarchical relationships between them.

Inheritance allows us to define a class in terms of another class, which makes it easier
to create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance

Single Inheritance: - Single Inheritance is method in which a derived class has only one
base class.

Example
#include <iostream.h>
class Value
{
protected:
int val;
public:
void set_values (int a)
{ val=a;}
};
class Cube: public Value
{
public:
int cube()
{ return (val*val*val); }
Object Oriented Programming

};
int main ()
{
Cube cub;
cub.set_values (5);
cout << "The Cube of 5 is::" << cub.cube() << endl;
return 0;
}

Result:

The Cube of 5 is:: 125

In example shows a Base class value and a Derived class cube


class value contain Protected member such As val
Protected access Specifier we can use in Derived class.
Private member can not be Inheriting.

2. Multiple Inheritance:- You can derive a class from any number of base classes. Deriving
a class from more than one direct base class is called multiple inheritance.
Multiple inheritance enables a derived class to inherit members from more than one
parent.
Deriving directly from more than one class is usually called multiple inheritance.

Syntax:-
Class C: Public A, Public B
{
Body of D

Prepared By: Dr.Vimal A. Vaiwala Page 14


Object Oriented Programming

Example
class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;

}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal: "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();}

Prepared By: Dr.Vimal A. Vaiwala Page 15


Object Oriented Programming

Output:
Enter the Roll no: 100
Enter two marks

90
80

Enter the Sports Mark: 90


Roll No: 100
Total : 260
Average: 86.66

Ambiguity: - In multiple inheritance the ambiguity arises when same method name is being
used by two derived class and further derivation from these two base classes.
To resolve this ambiguity we are using scope resolution operator.

class M
{
public:
void display()
{
cout<<"vimal \n";
}
};
class N
{
public:
void display()
{
cout<<"Vaiwala\n";
}
}
class P:public M,public N
{
public:
void display(void)
{
M::display();
N::display();

};
int main()
{

Prepared By: Dr.Vimal A. Vaiwala Page 16


Object Oriented Programming

clrscr();
P p;
p.display();
getch();
}

Output:
Vimal
Vaiwala

3. Hierarchical Inheritance: - It is the inheritance hierarchy wherein multiple subclasses


inherit from one base class
Hierarchical Inheritance is a method of inheritance where one or more derived classes
is derived from common base class.
It is the process of deriving two or more classes from single base class. And in turn
each of the derived classes can further be inherited in the same way.
The base class will include all the features that are common to the subclasses. A
subclass can be constructed by inheriting the properties of the base class. A subclass
can serve as a base class for the lower level classes and so on.

Example of Hierarchical representation of student life in University

Prepared By: Dr.Vimal A. Vaiwala Page 17


Object Oriented Programming

Syntax:-
class A
{
-------
-------
};
class B : visibility_label A
{
-------
-------
};
class C : visibility_label A
{
-------
-------
};
class D : visibility_label A
{
-------
-------
};

Here the visibility_label can be private, protected or public. If we do not specify any
visibility_label then by default is private.

class A
{
public:
int val;
void getvalue(int j)
{
val=j;
}
};
class B : public A
{
public:
void square()
{
cout<<endl<<val*val;
}
};
class C : public A
{
public:
void cube()

Prepared By: Dr.Vimal A. Vaiwala Page 18


Object Oriented Programming

{
cout<<endl<<val*val*val;
}
void main()
{
int i;
clrscr();
B b;
C c;
cin>>i;
b.getvalue(i);
b.square();
c.getvalue(i);
c.cube();
getch();
}

Output
2

4
8

4. Multilevel Inheritance: - The mechanism of deriving a class from another ‘derived class’
is known as multilevel inheritance.

It is the inheritance hierarchy wherein subclass acts as a base class for other classes.

Multilevel Inheritance is a method where a derived class is derived from another derived
class.

Example
class A
{
protected:
int x;
public:
Prepared By: Dr.Vimal A. Vaiwala Page 19
Object Oriented Programming

void showA()
{
cout<<"enter a value for x:"<<endl;
cin>>x;
}
};
class B:public A
{
protected:
int y;
public:
void showB()
{
cout<<"enter value for y:";
cin>>y;
}
};
class C:public B
{
public:
void showC()
{
showA();
showB();
cout<<"x*y ="<<x*y;
}
};
void main()
{
C ob1;
ob1.showc();
}
Output
Enter value of x = 12
Enter value of y = 3
X * Y =36

5. Hybrid Inheritance The inheritance hierarchy that reflects any legal combination of other
four types of inheritance.

There could be situations where we need to apply two or more types of inheritance to
design a program.

"Hybrid Inheritance" is a method where one or more types of inheritance are combined together and
used

Prepared By: Dr.Vimal A. Vaiwala Page 20


Object Oriented Programming

In figure base class A and class B and C are derived from class A. So that path is called
Hierarchical Inheritance.

Class B and C are the base class for class D. so that path is called multiple inheritance.
because there are more then one base class.

Example:-
class stu
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
out<<"Roll no"<<rno<<"\n";

Prepared By: Dr.Vimal A. Vaiwala Page 21


Object Oriented Programming

}
};
class test:public stu
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks obtained:"<<"part1="<<part1<<"\n"<<"part2="<<part2<<"\n";
}
};
class sports
{
protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<"sports:"<<score<<"\n";

}
};
class result: public test, public sports
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"Total Score="<<total<<"\n";
}

Prepared By: Dr.Vimal A. Vaiwala Page 22


Object Oriented Programming

int main()
{
clrscr();
result stu;
stu.get_no(123);
stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
}
OUTPUT
Roll no 123
Marks obtained : part1=27.5
Part2=33
Sports=6
Total score = 66.5

Explain Abstraction

Data abstraction refers to, providing only essential information to the outside word and
hiding their background details i.e. to represent the needed information in program without
presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation of
interface and implementation.

Real world Example


Let's take one real life example of a TV which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs, and DVD
players BUT you do not know it's internal detail that is, you do not know how it receives
signals over the air or through a cable, how it translates them, and finally displays them on
the screen.
Thus we can say, a television clearly separates its internal implementation from its external
interface.
Now if we talk in terms of C++ Programming, C++ classes provides great level of data
abstraction. They provide sufficient public methods to the outside world to play with the
functionality of the object and to manipulate object data ie. state without actually knowing
how class has been implemented internally.

Prepared By: Dr.Vimal A. Vaiwala Page 23


Object Oriented Programming

Reasons for the need of Abstraction

Flexibility in approach:

By hiding data or abstracting details that are not needed for presentation, the programmer
achieves greater flexibility in approach.

Enhanced Security:

Abstraction gives access to data or details that are needed by users and hide the
implementation details, giving enhanced security to application.

Easier Replacement:

With the concept of abstraction in object-oriented programming language, it is possible to


replace code without recompilation. This makes the process easier and saves time for users.

Modular Approach:

In object-oriented programming language C++, the abstraction concept helps users to divide
the project application into modules and test each of them separately. Then all modules are
integrated and ultimately tested together. This approach makes the application development
easier.

Q:-2 what is Polymorphism? Explain types of polymorphism.

Definition

It is a Greek term, means the ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of data used
in operation.

Real world example

A frog can live under water and outside the water also.

Practical example

Ex- For one operator operation ca take different from if operator is working on number ‘+’
than it gives sum of numbers & if this operation is working on string than it will give
concatenation string. This type of behavior is known as operator overloading.

Types of polymorphism

1. Runtime polymorphism

Resolving a function call at runtime is known as Runtime polymorphism.


Prepared By: Dr.Vimal A. Vaiwala Page 24
Object Oriented Programming

It is also known as dynamic or late or runtime binding.

It is achieved through virtual function.

2. Compile time polymorphism

Resolving a function call at compile time is known as Runtime polymorphism.

It is known as static or early or compiles time binding.

It is achieved through function overloading and operator overloading.

Function Overloading

Single function name can used to handle different number & different types of arguments.
Using single function name to perform different type of task is known as function
overloading.

Using Function overloading we can design a family of function with one function name
but with different argument lists.

The function would perform different operations on the argument list the function call.

The correct function to be invoked is determined by checking the number and type of the
arguments but not on the function type.

A function call first matches the prototype having the same number and type of argument and
then calls the appropriate function for execution. A best match must be unique.

Prepared By: Dr.Vimal A. Vaiwala Page 25


Object Oriented Programming

Example
//function prototyping
int volume(int);
double volume(double,int);
long volume(long,int,int);
main()
{
clrscr();
cout<<volume(10) <<"\n";
cout<<volume(2.5,8) <<"\n";
cout<<volume(100L,75,15) <<"\n";
getch();

}
//Function defination
int volume(int s) //cube
{
return (s*s*s);
}
double volume(double r,int h) //cylinder
{
return(3.14519*r*r*h);
}
long volume(long l,int b,int h) //rectangular
{
return (l*b*h);
}

Operator Overloading

Definition:-

C++ permits us to add two variables of user defined types with same syntax that is applied
to the basic types. This means that C++ has the ability to provide the operator with special
meaning for a data type.

i.e. The mechanism of giving such special meaning to an operator is known as operator
overloading.

Defining operator overloading

To define an additional task to an operator, we must specify what it means in relation to


the class to which the operator is applied.

Prepared By: Dr.Vimal A. Vaiwala Page 26


Object Oriented Programming

This is done with the help of a special function, called operator function, which describes
the task. The general form of an operator function is:

return type class name:: operator op(arg list)


{
Function body //task defined
}

Where return type of value returned by the specified operation and op is the operator
overloading being overloaded.

The op is preceded by the keyword operator. operator op is the function name.

A basic difference between them is that a friend function will have only one argument for
unary operators and two for binary operators, while a member function has no argument for
unary operators and two for binary operators, while a member function has no argument for
unary operators and one for binary operators.

The process of overloading involving the following steps:

1. Create a class the defines the data type that is to be used in overloading operation.
2. Declare the operator function operator op ( ) in the public part of the class.
3. Define the operator function to implement the required operations.

Rules for operating overloading

Only existing operators can be overloaded.

The overloaded operator must have at least one operand that is of user-defined type.

Overloaded operator follow syntax rules of original operators. They can not be overridden.

Following operators that can not be overloaded. (.membership operator, .* pointer-to-


member operator, :: scope resolution operator, ?: conditional operator

we can not use friend function to overload certain operators. = assignment operator, ( )
function call operator, [] subscription operator, class member access operator.

For Unary operator no argument and no return type but in friend function take one
reference argument.

For Binary operator overloaded through a member function, take one explicit argument
and those which are overloaded through a member function take two explicit argument.

Prepared By: Dr.Vimal A. Vaiwala Page 27


Object Oriented Programming

For Binary operators, the left hand operand must be an object of the relevant class.

For Binary operators must return a value.

Example:-

class increase
{

private:
int data;
public:
increase()
{
data=0;
}
int display()
{
cout<<data<<endl;
}
void operator++()
{
data++;
}
};
void main()
{
clrscr();
increase i1,i2;
i1.display();
i2.display();
i1++;
i2++;
i1.display();
i2.display();
getch();
}
Friend Function with operator overloading

Friend function may be used in place of member functions for overloading a binary
operator, the difference being that a friend function requires two arguments to be explicitly
passed to it, while a member function requires only one.

Prepared By: Dr.Vimal A. Vaiwala Page 28


Object Oriented Programming

Example
class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y)
{ a=x;
b=y;
}
void show()
{
cout<<a<<endl<<b<<endl;
}
friend myclass operator+(myclass,myclass);
};
myclass operator+(myclass ob1,myclass ob2)
{
myclass temp;
temp.a = ob1.a + ob2.a;
temp.b = ob1.b + ob2.b;
return temp;
}
void main()
{
clrscr();
myclass a(10,20);
myclass b(100,200);
a=a+b;
a.show();
getch();
}

Explain Virtual Function

A virtual function is a member function which is declared within a base class and is re-
defined (overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.

When we use the same function name in both base and derived classes, the function in
base class is declared as virtual using keyword virtual preceding its normal declaration.

Prepared By: Dr.Vimal A. Vaiwala Page 29


Object Oriented Programming

When a function is made virtual, C++ determines which function to use at run time based
by making the based on the type of object pointer to by base pointer, rather than the type
pointer. Thus, by making the base pointer to point to different objects, we can execute
different versions of the virtual function.

Example
class Base
{
public:
void display()
{
cout<<"\n Display base";
}
virtual void show()
{
cout<<"\n show base";
}
};
class Derived: public Base
{
public:
void display()
{
cout<<"\n Display Derived";
}
void show()
{
cout<<"\n show derived";
}
};
int main ()
{
clrscr();
Base B;
Derived D;
Base *bptr;
cout<<"\n bptr points to base \n";
bptr=&B;
bptr -> display();//call base version
bptr -> show();//call base version
cout<<"\n\n bptr points to derived \n";
bptr=&D;
bptr -> display();//calls base version
bptr -> show();//calls Derived version
return 0; }

Prepared By: Dr.Vimal A. Vaiwala Page 30


Object Oriented Programming

Output

bptr points to base


Display base
Show base
bptr points to Derived
Display base
Show derived

Rules for virtual function


1. The virtual function must be member of base class
2. They cannot be static members
3. They are accessed by using object pointers
4. Prototype of base class function & derived class must be same
5. Virtual function in base class must be defined even though it is not used
6. A virtual function can be friend function of another class
7. We could not have virtual constructor
8. If a virtual function is derived in base class, it need not be necessarily redefined in the
derived class
9. Pointer object of base class can point to any object of derived class but reverse is not true
10. When a base pointer points to derived class, incrementing & decrementing it will not
make it point to the next object of derived class

Explain Pure Virtual Function


A pure virtual function is a function declared in a base class that has no definition
relative to the base class. In such cases, the compiler requires each derived class to
either define the function or redeclare it as a pure virtual function
To create a pure virtual function, rather than define a body for the function, we
simply assign the function the value 0.
If you have a pure virtual, the class becomes abstract. You cannot create an object of
it.

Example
class base
{
public:
//pure virtual function
virtual void show()=0;
};
class derived1 : public base
{
public:
void show()
{
cout<<"\n Derived 1";
}

Prepared By: Dr.Vimal A. Vaiwala Page 31


Object Oriented Programming

};
void main()
{
base *b; derived1 d1;
b = &d1;
b->show();
}

Output
Derived1

Explain Abstract Class


An abstract class is one that is not used to create objects. An abstract class is designed only
to act as a base class.
It is a design concept in program development and provides a base upon which other
classes may be built.
Allows the base class to provide only an interface for its derived classes.
Prevents anyone from creating an instance of this class.
A class is made abstract if at least one pure virtual function defined.

Note: - Take above example

Prepared By: Dr.Vimal A. Vaiwala Page 32

You might also like