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

CS2311-Object Oriented Programming VSAGI

OPERATOR OVERLOADING:

Operator overloading is a technique used to change the predefined operation of an


operator for existing data types to a new operator for user defined data types.
All the operators can be overloaded except the operators given below

Conditional Operator ?:
Scope resolution operator ::
Class Member operator .*
Size of Operator sizeof
Membership operator .

Defining operator overloading:

Overloading can be defined inside the class (or) outside the class.
If defined outside, it should be declare inside using prototype.

General Form:

i) Defining inside the class:


Return type operator symbol(argument list)
{


}
ii) Defining outside the class:

(a)Declaration inside the class:

Return type operator symbol(argument list);

(b)Definition outside the class:

Returntype classname::operator symbol(list of arguments)

Unit-II Page 1
CS2311-Object Oriented Programming VSAGI

{
..
}

iii) Calling the overloaded function:


1. We can call the defined overloaded function in two ways. They are
1. objectname symbol;
2. objectname= objectname symbol; (or)
= symbol objectname;(or)
= objectname symbol objectname;

Where,

Operator-keyword

Symbol-valid operator symbol like + - * etc.,

Rules:

1. Operator overloading function should be a public member function (or) friend


function.
2. Unary ++,-- can be called by prefix (or) postfix form.
Operators are classified into
o Unary operator.
o Binary Operator.

OVERLOADING UNARY OPERATOR:

If the symbol used in a operator overloading function is a unary operator (-, +, ++,--)
then this overloading is called unary operator overloading.

Example:

Class space

Unit-II Page 2
CS2311-Object Oriented Programming VSAGI

int x,y,z;

public:

void getdata(int a,int b,int c);

void display(void);

void operator (); //unary minus overloaded

};

void space::getdata(int a,int b,int c)


Output:
{
s : X=10 Y=-20 Z=30
x=a;y=b;z=c;
-s: X=-10 Y=20 Z=-30
}

void space::display(void)

Cout<<X=<<x;

Cout<<Y=<<y;

Cout<<Z=<<z;

int main()

space s;

s.getdata(10,-20,30);

cout<<s;

Unit-II Page 3
CS2311-Object Oriented Programming VSAGI

s.display();

-s; //activates operator () function

cout<<-s;

s.display();

return 0;

OVERLOADING BINARY OPERATOR:

It the symbol used in a operator overloading function is a binary operator (+,-,*,/,+=,-


=,etc) then this overloading is called binary operator overloading.

Example:

Class complex

float x,y;

public:

complex() {} //constructor1

complex(float real,float imag) //constructor2

x=real;y=imag;

complex operator +(complex);

};

complex complex::operator +(complex c)


Unit-II Page 4
CS2311-Object Oriented Programming VSAGI

complex temp;

temp.x=x+c.x; //temporary these are float additions

temp.y=y+c.y;

return(temp);

void complex::display(void)

Cout<<x<<+j<<y<<\n;

int main()

complex c1,c2,c3;

c1=complex(2.5,3.5);

c2=complex(1.6,2.7);

c3=c1+c2;

cout<<C1=;c1.display();

cout<<C2=;c2.display();

cout<<C3=;c3.display();

return 0;

Unit-II Page 5
CS2311-Object Oriented Programming VSAGI

Output:

C1=2.5+j3.5

C2=1.6+j2.7

C3=4.1+j6.2

OVERLOADING THROUGHT FRIEND FUNCTION:

Overloading binary operators using friends:

We can overload a binary operator, using ordinary function with the help of friend
operator.
This is called overloading binary operators with friend.
The difference between overloading operators using member function and using
friend function requires two arguments.

General Form:

Class classname

Private:

Public:

friend returntype operator symbol(datatype1,datatype2);

};

Unit-II Page 6
CS2311-Object Oriented Programming VSAGI

returntype operator symbol(datatype1 arg1,datatype2 arg2)

..

Where,

Friend,operator-keyword

Calling Overload function:

General form

Object3=object1 symbol object2;

When this statement is executed the symbol calls the overload function and the value
of object1 and object2 are supplied to the overload function because it is not a
member function.
Finally the calculated value will be assigned to object3 in the left hand side.

Rules:

1. It requires two arguments.


2. The symbol in the class and in the overload function should be same.
3. Same operator can be overload for different data type argument list.
4. All the operators can be overloaded using friend except the operator given below
o Assignment operator =
o Function call operator ()
o Class member class operator ->
o Subscripting operator []

Example:

Class interest

Unit-II Page 7
CS2311-Object Oriented Programming VSAGI

int year;

float amount,rate;

public:

interest()

year=5; amount=0.0; rate=10.0;

void read()

Cout<<Enter the amount:;

Cin>>amount;

void print()

Cout<<\nYEAR=<<year;

Cout<<\nAMOUT=<<amount;

Cout<<\nRATE=<<rate;

Cout<<\nTOTAL INTEREST=<<(year*amont*rate)\100;

friend interest operator +(interest,interest); //friend function

Unit-II Page 8
CS2311-Object Oriented Programming VSAGI

};

interest operator +(interest i1,interest i2)

interest t;

t.amount=i1.amount+i2.amount;

return(t);

void main()

interest i1,i2,i3;

i1.read();

i2.read();

i3=i1+i2; //calling friend function

i1.print();

i2.print();

i3.print();

Unit-II Page 9
CS2311-Object Oriented Programming VSAGI

Output:

i1.read() Enter the amount=1000

i2.read() Enter the amount=2000

i1.print() YEAR=5

AMOUNT=1000

RATE=10

TOTAL INTEREST=500

i2.print() YEAR=5

AMOUNT=2000

RATE=10

TOTAL INTEREST=1000

i3.print() YEAR=5

AMOUNT=3000

RATE=10

TOTAL INTEREST=1500

You can overload any of the following operators:


Overloading Operator

+ - * / % ^ & | ~

! = < > += -= *= /= %=

Unit-II Page 10
CS2311-Object Oriented Programming VSAGI

^= &= |= << >> <<= >>= == !=

<= >= && || ++ -- , ->* ->

() [] New delete new[] delete[]

where () is the function call operator and [] is the subscript operator. It can overload both the
unary and binary forms of the following operators:

+ - * &

It cannot overload the following operators:

. .* :: ?:

It cannot overload the preprocessor symbols # and ##.


An operator function can be either a nonstatic member function, or a nonmember
function with at least one parameter that has class, reference to class, enumeration, or
reference to enumeration type.
It cannot change the precedence, grouping, or the number of operands of an operator.
An overloaded operator (except for the function call operator) cannot have default
arguments or an ellipsis in the argument list.
It must declare the overloaded =, [], (), and -> operators as nonstarter member
functions to ensure that they receive values as their first operands.
The operators new, delete, new [], and delete [] do not follow the general rules
described in this section. All operators except the = operator are inherited.

C++ FRIEND FUNCTIONS


Need for Friend Function:
As discussed in the earlier sections on access specifiers, when a data is declared
as private inside a class, then it is not accessible from outside the class.
A function that is not a member or an external class will not be able to access
the private data.

Unit-II Page 11
CS2311-Object Oriented Programming VSAGI

A programmer may have a situation where he or she would need to access private data
from non-member functions and external classes.
For handling such cases, the concept of Friend functions is a useful tool.
What is a Friend Function?
A friend function is used for accessing the non-public members of a class.
A class can allow non-member functions and other classes to access its own private
data, by making them friends.
Thus, a friend function is an ordinary function or a member of another
class.
How to define and use Friend Function in C++?
The friend function is written as any other normal function, except the
function declaration of these functions is preceded with the keyword friend.
The friend function must have the class to which it is declared as friend passed to it in
argument.
Some important points to note while using friend functions in C++:
The keyword friend is placed only in the function declaration of the
friend function and not in the function definition.
It is possible to declare a function as friend in any number of classes.
When a class is declared as a friend, the friend class has access to the
private data of the class that made this a friend.
A friend function, even though it is not a member function, would have
the rights to access the private members of the class.
It is possible to declare the friend function as either private or public.
The function can be invoked without the use of an object. The friend
function has its argument as objects, seen in example below.
Example to understand the friend function:
#include <iostream.h>
class exforsys
{
private:
int a,b;

Unit-II Page 12
CS2311-Object Oriented Programming VSAGI

public:
void test()
{
a=100;
b=200;
}
friend int compute(exforsys e1)
//Friend Function Declaration with keyword friend and with the object of class exforsys to
which it is friend passed to it
};
int compute(exforsys e1)
{
//Friend Function Definition which has access to private data return int(e1.a+e2.b)-5;
}
main()
{
exforsys e;
e.test();
cout<<The result is: << e;
//calling of friend function with object as argument
}
Output:
The result is:295

TYPING CONVERSION AND VISIBILITY

It is the process of converting one type into another.


In other words converting an expression of a given type into another is called type
casting.
There are two ways of achieving the type conversion namely:
1. Automatic Conversion (or) Implicit Conversion
2. Type casting (or) Explicit Conversion

Unit-II Page 13
CS2311-Object Oriented Programming VSAGI

Automatic Conversion:

This is not done by any conversions or operators.


In other words the value gets automatically converted to the specific type to which it
is assigned.
#include <iostream>
using namespace std;
void main()
{
short x=6000;
int y;
y=x;
}
In the above example the data type short namely variable x is converted to int and is
assigned to the integer variable y.
So as above it is possible to convert short to int, int to float and so on.
Type casting:

Explicit conversion can be done using type cast operator. The general syntax for
doing this is :
data type (expression);

Here in the above data type is the type which the programmer wants the expression to
gets changed as.
In C++ the type casting can be done in either of the two ways mentioned below
namely:
C-style casting
C++-style casting
The C-style casting takes the syntax as
(Type) expression
This can also be used in C++.

Apart from the above, the other form of type casting that can be used specifically in
C++ programming language namely C++-style casting is as below namely:

Unit-II Page 14
CS2311-Object Oriented Programming VSAGI

Type (expression)

This approach was adopted since it provided more clarity to the C++ programmers
rather than the C-style casting. Say for instance the as per C-style casting
(type) firstVariable * secondVariable is not clear but when a programmer uses the
C++ style casting it is much more clearer as below
type (firstVariable) * secondVariable

Let us see the concept of type casting in C++ with a small example:
#include <iostream>
using namespace std;
void main()
{
int a;
float b,c;
cout << "Enter the value of a:";
cin >> a;
cout << "Enter the value of b:";
cin >> b;
c = float(a)+b;
cout << "The value of c is:" << c;
}

In the above program ais declared as integer and b and c are declared as float. In the
type conversion statement namely
c = float (a) +b;

The variable a of type integer is converted into float type and so the value 10 is
converted as 10.0 and then is added with the float variable b with value 12.5 giving a
resultant float variable c with value as 22.5.

Unit-II Page 15
CS2311-Object Oriented Programming VSAGI

TEMPLATE:
Template is a generalized form of reusable modules such as classes, functions
etc., in c++.
Template is also called generics or parameterized types.
Programming with templates is also called as generic programming.

Uses:

1. It supports all data types.


2. It reduces the number of function (or) classes in a program. This means with
the help of single function (or) class we can do number of operations with
different data type.

Types of Template:

1. Function template.
2. Class Template.

FUNCTION TEMPLATE:

Function template enables us to create a family of functions with different argument


types.
(or)
A c++ language constructs that allows the complier to generate multiple versions of a
function by allowing parameterized datatypes.

General Form:

template <class T>

returntype functionname(list of arguments)

//body of function with type T

Unit-II Page 16
CS2311-Object Oriented Programming VSAGI

Example:

template<class T>

T add(T a,T b)

T s;

s=a+b;

return s;

Invocation of function template:

The defined function template is called as ordinary function

General form:

i) functiontemplatename(list of argument values);


ii) var=functiontemplatename(list of argument values);

where,

functiontemplatename-name of the already defined function template

list of argument values-actual values which are given to the arguments in the function
template.

Example:

#include<iostream.h>

template <class T>

Unit-II Page 17
CS2311-Object Oriented Programming VSAGI

T sum(T a,T b)

T s;

s=a+b;

return s;

void main()

int a1,b1,c1;

float a2,b2,c2;

cout<<Enter two interger numbers:);

cin>>a1>>b1;

c1=sum(a1,b1);

cout<<Enter two float numbers:);

cin>>a2>>b2;

c2=sum(a2,b2);

cout<<interger sum is:<<c1<<endl;

cout<<Float sum is:<<c2<<endl;

Execution:

Enter two integer numbers:5 3

Unit-II Page 18
CS2311-Object Oriented Programming VSAGI

a1=5 b1=3

c1=sum(5,3)

it calls the sum function.Now the template datatype T becomes integer.

Enter two floatnumbers:7.5 6.5

a1=7.5 b1=6.5

c1=sum(7.5,6.5)

it calls the sum function.Now the template datatype T becomes float

OVERLOADING OF TEMPLATE FUNCTION:

Overloading template function means defining different template functions with same
name.
Template functions are overloaded by defining other template functions (or) ordinary
functions.
That is to overload template function we need atleast one template function.

Execution procedure:

While calling it searches for a matched ordinary overload function(Matched with the
help of number of arguments and type).
If there is no match in ordinary overload function it searches for a matched overload
template function.

Example:

#include<iostream.h>

#inlcude<conio.h>

template<class T>

T sum(T a,T b)

Unit-II Page 19
CS2311-Object Oriented Programming VSAGI

T s=a+b;

return s;

template<class T1>

T1 sum(T1 a)

T1 s=a+100;

return s;

int sum(int a,int b)

int s=a+b;

return s;

void main()

int i1,i2; float f1,f2;

cout<<Enter interger number:;

cin>>i1;

cout<<sum=<<sum(i1);

Unit-II Page 20
CS2311-Object Oriented Programming VSAGI

cout<<Enter float number:;

cin>>f1;

cout<<sum=<<sum(f1);

cout<<Enter interger and integer numbers:;

cin>>i1>>i2;

cout<<sum=<<sum(i1,i2);

cout<<Enter float and float number:;

cin>>f1>>f2;

cout<<sum=<<sum(f1,f2);

CLASS TEMPLATE

A c++ language construct that allows the compiler to generate multiple versions of a
class by allowing parameterized data type.
The class template is also called as generic class (or) class generator.

General form:

template<class T>

class classname

{ //Body of the class };

Example:

template<class T>

class emp

Unit-II Page 21
CS2311-Object Oriented Programming VSAGI

Char name[30];

T salary;

public:

void read()

{ cin>>name>>salary; }

T pay()

{ return salary; }

};

Declaration of objects for class template:

A class created from a class template is called a template class.

Syntax:

Classname<type>objectname(arglist);

This process of creating a specific class from a class template is called


instantiation.

Example:

template<class T>

class emp

Char name[30];

T salary;

public:

void read()
Unit-II Page 22
CS2311-Object Oriented Programming VSAGI

{ cin>>name>>salary; }

T pay()

{ return salary; }

};

void main()

emp <int> e1;

emp <float> e2;

emp <double> e3;

cout<<Enter the name and integer salary=;

e1.read();

cout<<e1.pay();

cout<<Enter the name and float salary=;

e2.read();

cout<<e2.pay();

cout<<Enter the name and double salary=;

e3.read();

cout<<e3.pay();

Unit-II Page 23
CS2311-Object Oriented Programming VSAGI

CLASS TEMPLATE WITH MULTIPLE PARAMETERS (TEMPLATE


ARGUMENT):

The class template contains more than one template data type.
Using this we can declare more than one general datatype inside the class.

General form:

Template<class T1,class T2>

Class classname

//body of the class

};

Example:

template <class T1,class T2>

class sum

T1 a; T2 b;

public:

void read()

cin>>a>>b;

void sum()

Unit-II Page 24
CS2311-Object Oriented Programming VSAGI

Cout<<\n sum=<<a+b<<endl;

};

void main()

Sum <<int,int> s1;

Sum<int,float> s2;

cout<<enter two integer numbers:;

s1.read(); s1.sum();

s2.read(); s2.sum();

Member function template:

All member functions inside a class template is called member function


template.
The arguments of the class template are common for all member functions.
If the member function is not an inline function, it should be declared inside
the class and defined outside the class.

General form:

i) Declaration: returntype functionname(arguments list);


ii) Definction: template<class T1,class T2,..>

Returntype
classname<T1,T2,>::functionname(argumentlist)

{.}

Unit-II Page 25
CS2311-Object Oriented Programming VSAGI

Example:

Template<class T>

Class array

T a[100];

Int n;

Public:

Void read();

Void sum();

};

Template <class T>

Void array<T>::read()

cout<<Enter the number of data:;

cin>>n;

cout<<Enter the number of data one by one:;

for(int i=0;i<n;i++)

cin>>a[i];

template<class T>

void array<T>::sum()

Unit-II Page 26
CS2311-Object Oriented Programming VSAGI

T sum=0;

for(int i=0;i<n;i++)

sum+=a[i];

cout<sum=<<sum;

Void main()

array <int> s1;

array<float>s2;

cout<<Integer process;

s1.read(); s1.sum();

cout<<Float process;

s2.read(); s2.sum();

INHERITANCE

Inheritance is the process of forming a new class from an existing class or base class.
The base class is also known as parent class or super class, the new class that is
formed is called derived class.
Derived class is also known as a child class or sub class
. Inheritance helps in reducing the overall code size of the program, which is an
important concept in object-oriented programming.

Unit-II Page 27
CS2311-Object Oriented Programming VSAGI

For example, a programmer can create a base class named fruit and define derived
classes as mango, orange, banana, etc.
Each of these derived classes, (mango, orange, banana, etc.) has all the features of the
base class (fruit) with additional attributes or features specific to these newly created
derived classes.
Mango would have its own defined features, orange would have its own defined
features, banana would have its own defined features, etc. This concept of Inheritance
leads to the concept of polymorphism.

Features or Advantages of Inheritance:


Reusability
o Inheritance helps the code to be reused in many situations.
o The base class is defined and once it is compiled, it need not be reworked.
o Using the concept of inheritance, the programmer can create as many derived classes
from the base class as needed while adding specific features to each derived class as
needed.
Saves Time and Effort
o Reusability achieved by inheritance saves the programmer time and effort, because
the main code written can be reused in various situations as needed.
Increases Program Structure which results in greater reliability.
Polymorphism

General Format for implementing the concept of Inheritance:


Syntax:
Class derived_classname: access specifier base classname
Example:
If the base class is exforsys and the derived class is sample it is specified as:
Class sample: public exforsys
The above makes sample have access to both public and protected variables of base
class exforsys.
Reminder, about public, private and protected is access specifier.

Unit-II Page 28
CS2311-Object Oriented Programming VSAGI

If a member or variables defined in a class is private, then they are accessible by members
of the same class only and cannot be accessed from outside the class. .
Public members and variables are accessible from outside the class. .
Protected access specifier is a stage between private and public. If a member functions or
variables defined in a class are protected, then they cannot be accessed from outside the
class but can be accessed from the derived class.
Inheritance Example:
class exforsys
{
private:
int x;
public:
exforsys(void) { x=0; }
void f(int n1)
{
x= n1*5;
} void output(void) { cout<<x; }
};
class sample: public exforsys
{
public:
sample(void) { s1=0; }
void f1(int n1)
{
s1=n1*10;
}
void output(void)
{

exforsys::output();
cout << s1;
}

Unit-II Page 29
CS2311-Object Oriented Programming VSAGI

priv
ate:
int
s1;
};
int
main(void
)
{
sample s;
s.f(10);
s.output();
s.f1(20);
s.output();
}
In the above example, the derived class is sample and the base class is exforsys.
The derived class defined above has access to all public and private variables.
Derived classes cannot have access to base class constructors and destructors.
The derived class would be able to add new member functions, or variables, or new
constructors or new destructors.
In the above example, the derived class sample has new member function f1( ) added in
it. The line:
Sample s;
creates a derived class object named as s.
When this is created, space is allocated for the data members inherited from the base
class exforsys and space is additionally allocated for the data members defined in the
derived class sample.
The base class constructor exforsys is used to initialize the base class data members and
the derived class constructor sample is used to initialize the data members defined in
derived class.
The access specifier specified in the line:

Unit-II Page 30
CS2311-Object Oriented Programming VSAGI

class sample: public exforsys


Public indicates that the public data members which are inherited from the base class by
the derived class sample remains public in the derived class.

A derived class inherits every member of a base class except:


its constructor and its destructor
its friends
its operator=() members

OVERVIEW OF DERIVED CLASSES

New classes can be derived from existing classes using a mechanism called
"inheritance"
Classes that are used for derivation are called "base classes" of a particular derived
class. A derived class is declared using the following syntax:
class Derived : [virtual] [access-specifier] Base
{
// member list
};
class Derived : [virtual] [access-specifier] Base1,
[virtual] [access-specifier] Base2 . . .
{
// member list
};

After the tag (name) for the class, a colon appears followed by a list of base
specifications.
The base classes so named must have been declared previously.
The base specifications may contain an access specifier, which is one of the keywords
public, protected or private.
These access specifiers appear before the base class name and apply only to that base
class.

Unit-II Page 31
CS2311-Object Oriented Programming VSAGI

These specifiers control the derived class's permission to use to members of the base
class.
See Member-Access Control for information on access to base class members.
If the access specifier is omitted, the access to that base is considered private.
The base specifications may contain the keyword virtual to indicate virtual
inheritance.
This keyword may appear before or after the access specifier, if any.
If virtual inheritance is used, the base class is referred to as a virtual base class.
Multiple base classes can be specified, separated by commas.
If a single base class is specified, the inheritance model is Single inheritance .
If more than one base class is specified, the inheritance model is called Multiple
inheritance.

TYPES OF INHERITANCE
There are five different inheritances supported in C++:

(1) Simple / Single

(2) Multilevel

(3) Hierarchical

(4) Multiple

(5) Hybrid

Unit-II Page 32
CS2311-Object Oriented Programming VSAGI

Figure 3.1 Types of Inheritance

Inheritance is the concept to inherit the properties of one class to another class. This
has also known as class structure again.
For example, classes A contains two-member function ads and subtracts and class b
contain two another functions multiply and divide. We want to use all these function
with one object then we need to use inheritance where class B inherits all the property
of class, which is public, but class B cannot use the private properties of class A.

Inheritance Mode
1. Single Inheritance:

When class a gas inherited in class has known as base class and B class is known as
derived class. Here only two classes have linked to each other.

Unit-II Page 33
CS2311-Object Oriented Programming VSAGI

Figure 3.3 Single Inheritance

2. Multilevel Inheritance:

In this type of inheritance, there are number of level and it has used in that cases
where we want to use all properties in number of levels according to the requirement.
For example, class A inherited in class b and class b has inherited in class c for class
b so on. Where class A is base class c.
In another way we can say b is derived class a base class for c and a indirect base
class for c is indirect base class for c and c indirect derived class for class A.

C
Interface path

Multilevel Inheritance
3. Multiple Inheritances:

In this type of inheritance, number of classes has inherited in a single class.


Where two or more classes are, know as base class and one is derive class.

Unit-II Page 34
CS2311-Object Oriented Programming VSAGI

Multiple Inheritances
4. Hierarchical Inheritance:

This type of inheritance helps us to create a baseless for number of classes and those
numbers of classes can have further their branches of number of class.

Hierarchical Inheritance
5. Hybrid Inheritance:

Unit-II Page 35
CS2311-Object Oriented Programming VSAGI

In this type of inheritance, we can have mixture of number of inheritances but this can
generate an error of using same name function from no of classes, which will bother
the compiler to how to use the functions.
Therefore, it will generate errors in the program. This has known as ambiguity or
duplicity.

Hybrid Inheritance
POLYMORPHISM

Polymorphism is the phenomenon where the same message sent to two different
objects produces two different set of actions.
Polymorphism is broadly divided into two parts:
Static polymorphism exhibited by overloaded functions.
Dynamic polymorphism exhibited by using late binding.
Static Polymorphism:

Static polymorphism refers to an entity existing in different physical forms


simultaneously.
Static polymorphism involves binding of functions based on the number, type, and
sequence of arguments.
The various types of parameters are specified in the function declaration, and
therefore the function can be bound to calls at compile time.
This form of association is called early binding.

Unit-II Page 36
CS2311-Object Oriented Programming VSAGI

The term early binding stems from the fact that when the program is executed, the calls
are already bound to the appropriate functions.
The resolution of a function call is based on number, type, and sequence of arguments
declared for each form of the function.
Consider the following function declaration: void add (int , int); void add(float, float);
When the add() function is invoked, the parameters passed to it will determine which
version of the function will be executed. This resolution is done at compile time.
Dynamic Polymorphism:

Dynamic polymorphism refers to an entity changing its form depending on the


circumstances.
A function is said to exhibit dynamic polymorphism when it exists in more than one
form, and calls to its various forms are resolved dynamically when the program is
executed.
The term late binding refers to the resolution of the functions at run-time instead of
compile time.
This feature increases the flexibility of the program by allowing the appropriate
method to be invoked, depending on the context.
Static Vs Dynamic Polymorphism:

Static polymorphism is considered more efficient and dynamic polymorphism more


flexible.
Statically bound methods are those methods that are bound to their calls at compile
time. Dynamic function calls are bound to the functions during run-time. This
involves the additional step of searching the functions during run-time. On the other
hand, no run-time search is required for statically bound functions.
As applications are becoming larger and more complicated, the need for flexibility is
increasing rapidly. Most users have to periodically upgrade their software, and this
could become a very tedious task if static polymorphism is applied. This is because
any change in requirements requires a major modification in the code. In the case of

Unit-II Page 37
CS2311-Object Oriented Programming VSAGI

dynamic binding, the function calls are resolved at run-time, thereby giving the user
the flexibility to alter the call without having to modify the code.
To the programmer, efficiency and performance would probably be a primary
concern, but to the user, flexibility or maintainability may be much more important.
The decision is thus a trade-off between efficiency and flexibility.

VIRTUAL FUNCTIONS
Introduction to Virtual Functions:

Polymorphism, one of the three main attributes of an OOP language, denotes a


process by which different implementations of a function can be accessed by the use
of a single name.
Polymorphism also means one interface, multiple methods.
C++ supports polymorphism both at run-time and at compile-time.
The use of overloaded functions is an example of compile-time polymorphism.
Run-time polymorphism can be achieved by the use of both derived classes and
virtual functions.
How does C++ handle these multiple versions of a function?

Based on the parameters being passed, the program determines at run-time which
version of the virtual function should be the recipient of the reference.
It is the type of object being pointed to, not the type of pointer, that determines
which version of the virtual function will be executed.
To make a function virtual, the virtual keyword must precede the function
declaration in the base class.
The redefinition of the function in any derived class does not require a second use
of the virtual keyword.
A virtual function is a member function that is declared within a base class and
redefined by a derived class.
To create virtual function, precede the functions declaration in the base class with
the keyword virtual.
When a class containing virtual function is inherited, the derived class redefines
the virtual function to suit its own needs.
Unit-II Page 38
CS2311-Object Oriented Programming VSAGI

Base class pointer can point to derived class object.


In this case, using base class pointer if we call some function which is in both
classes, then base class function is invoked.
But if we want to invoke derived class function using base class pointer, it can be
achieved by defining the function as virtual in base class, this is how virtual
functions support runtime polymorphism.

Declaration of virtual function:


Virtual functions are member functions declared with the keyword virtual.
For example, the general syntax to declare a Virtual Function uses:
Sample Code

1. Class class_name //This denotes the base class of C++ virtual function
2. {
3. Public:
4. Virtual void member function name() //This denotes the C++ virtual function
5. {
6. .
7. .
8. }
9. };

Example:
#include <iostream.h>
using namespace std;
class bclass
{
public: virtual void whichone()
{ cout << bclass\n;
} };
class dclass1 : public bclass

Unit-II Page 39
CS2311-Object Oriented Programming VSAGI

{ public: void whichone()


{ cout << dclass1\n;
} };
class dclass2 : public bclass
{ public: void whichone()
{ cout << dclass2\n;
} };
int main()
{
bclass Obclass;
bclass *p;
dclass1 Odclass1;
dclass2 Odclass2; // point to bclass
p = &Obclass; // access bclasss whichone()
p->whichone(); // point to dclass1
p = &Odclass1; // access dclass1s whichone()
p->whichone(); // point to dclass2
p = &Odclass2; // access dclass2s whichone()
p->whichone();
return 0;
}
Notice how the type of the object being pointed to, not the type of the pointer itself,
determines which version of the virtual whichone() function is executed.
Need for virtual function:
The vital reason for having a virtual function is to implement a different functionality
in the derived class.
For example: a Make function in a class Vehicle may have to make a Vehicle with red
color.
A class called Four-wheeler, derived or inherited from Vehicle, may have to use a
blue background and 4 tires as wheels.

Unit-II Page 40
CS2311-Object Oriented Programming VSAGI

For this scenario, the Make function for Four-wheeler should now have a different
functionality from the one at the class called Vehicle. This concept is called Virtual
Function.
Properties of Virtual Functions:
Dynamic Binding Property
Simple member functions. The main difference between a non-virtual C++ member
function and a virtual member function is in the way they are both resolved. A non-
virtual C++ member function is resolved during compile time or static binding.
Virtual Functions are resolved during run-time or dynamic binding.

Unit-II Page 41

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