Академический Документы
Профессиональный Документы
Культура Документы
OPERATOR OVERLOADING:
Conditional Operator ?:
Scope resolution operator ::
Class Member operator .*
Size of Operator sizeof
Membership operator .
Overloading can be defined inside the class (or) outside the class.
If defined outside, it should be declare inside using prototype.
General Form:
Unit-II Page 1
CS2311-Object Oriented Programming VSAGI
{
..
}
Where,
Operator-keyword
Rules:
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 display(void);
};
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();
cout<<-s;
s.display();
return 0;
Example:
Class complex
float x,y;
public:
complex() {} //constructor1
x=real;y=imag;
};
complex temp;
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
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:
};
Unit-II Page 6
CS2311-Object Oriented Programming VSAGI
..
Where,
Friend,operator-keyword
General form
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:
Example:
Class interest
Unit-II Page 7
CS2311-Object Oriented Programming VSAGI
int year;
float amount,rate;
public:
interest()
void read()
Cin>>amount;
void print()
Cout<<\nYEAR=<<year;
Cout<<\nAMOUT=<<amount;
Cout<<\nRATE=<<rate;
Cout<<\nTOTAL INTEREST=<<(year*amont*rate)\100;
Unit-II Page 8
CS2311-Object Oriented Programming VSAGI
};
interest t;
t.amount=i1.amount+i2.amount;
return(t);
void main()
interest i1,i2,i3;
i1.read();
i2.read();
i1.print();
i2.print();
i3.print();
Unit-II Page 9
CS2311-Object Oriented Programming VSAGI
Output:
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
+ - * / % ^ & | ~
! = < > += -= *= /= %=
Unit-II Page 10
CS2311-Object Oriented Programming VSAGI
where () is the function call operator and [] is the subscript operator. It can overload both the
unary and binary forms of the following operators:
+ - * &
. .* :: ?:
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
Unit-II Page 13
CS2311-Object Oriented Programming VSAGI
Automatic Conversion:
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:
Types of Template:
1. Function template.
2. Class Template.
FUNCTION TEMPLATE:
General Form:
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;
General form:
where,
list of argument values-actual values which are given to the arguments in the function
template.
Example:
#include<iostream.h>
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;
cin>>a1>>b1;
c1=sum(a1,b1);
cin>>a2>>b2;
c2=sum(a2,b2);
Execution:
Unit-II Page 18
CS2311-Object Oriented Programming VSAGI
a1=5 b1=3
c1=sum(5,3)
a1=7.5 b1=6.5
c1=sum(7.5,6.5)
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 s=a+b;
return s;
void main()
cin>>i1;
cout<<sum=<<sum(i1);
Unit-II Page 20
CS2311-Object Oriented Programming VSAGI
cin>>f1;
cout<<sum=<<sum(f1);
cin>>i1>>i2;
cout<<sum=<<sum(i1,i2);
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
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; }
};
Syntax:
Classname<type>objectname(arglist);
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()
e1.read();
cout<<e1.pay();
e2.read();
cout<<e2.pay();
e3.read();
cout<<e3.pay();
Unit-II Page 23
CS2311-Object Oriented Programming VSAGI
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:
Class classname
};
Example:
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,float> s2;
s1.read(); s1.sum();
s2.read(); s2.sum();
General form:
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();
};
Void array<T>::read()
cin>>n;
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<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.
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
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++:
(2) Multilevel
(3) Hierarchical
(4) Multiple
(5) Hybrid
Unit-II Page 32
CS2311-Object Oriented Programming VSAGI
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
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:
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:
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:
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:
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
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
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