Object Oriented
Programming
Knowledge Level:
Basic
About the Author
Created By: Cognizant Academy
Version and OOPSCONCPT/PPT/0404/1.0
Date:
©Copyright 2004, Cognizant Academy, All Rights Reserved 2
Courseware Information
Course Description •After completing this course, you will be able to
understand the importance of OOPS in programming
paradigm
•Basic Terminology’s involved into OOPS.
Level Basic
Prerequisites A participant must know basic understanding of
programming to do this course
©Copyright 2004, Cognizant Academy, All Rights Reserved 3
Course Objective & Outline
Course Objective:
After completing this course, you will be able to understand the
importance of OOPS in programming paradigm and basic terminology’s
involved into OOPS.
Course Flow:
1 2 3 4
Programming OOPS Functions in Classes and
paradigms Concepts C++ Objects
5 6
Inheritance Polymorphism
©Copyright 2004, Cognizant Academy, All Rights Reserved 4
1 Programming Paradigms : Overview
Introduction:
Paradigm: (One that serves as a pattern or model)
• A set of scientific and metaphysical beliefs that make up a
theoretical framework within which scientific theories can be
tested, evaluated, and if necessary revised" (Cambridge
dictionary of philosophy).
• A set of assumptions, concepts, values, and practices that
constitutes a way of viewing reality for the community that
shares them, especially in an intellectual discipline.
©Copyright 2004, Cognizant Academy, All Rights Reserved 5
Programming Paradigms : Overview
Programming paradigm:
• A paradigmatic style of programming (compare with a
methodology which is a paradigmatic style of doing software
engineering).
• Provides (and determines) the view that the programmer has
of the execution of the program.
©Copyright 2004, Cognizant Academy, All Rights Reserved 6
Programming Paradigms : Overview
Objective:
After completing this module, you will be able to understand
the following programming paradigms.
1. Procedural programming
2. Structured programming
3. Modular programming
4. Functional programming
5. Object-oriented programming
©Copyright 2004, Cognizant Academy, All Rights Reserved 7
Procedural Programming
• Conventional top-down approach
• Programming paradigm based upon the concept of the
procedure call (Procedures - also known as routines,
subroutines, Sub-programs, methods, or functions)
Global data
Sub-programs
©Copyright 2004, Cognizant Academy, All Rights Reserved 8
Procedural Programming
• Works well for small programs and individual algorithms
• Significant ease of maintainability and readability of code
• More flexible code
Possible benefits:
• The ability to re-use the same code at different places in the
program without copying it.
• An easier way to keep track of program flow than a collection
of "GOTO" or "JUMP" statements.
• The ability to be strongly modular or structured.
©Copyright 2004, Cognizant Academy, All Rights Reserved 9
Structured Programming
• Can be seen as a subset or sub discipline of Procedural
programming.
• A hierarchy of modules is used, each having a single entry
and a single exit point, in which control is passed downward
through the structure without unconditional branches to
higher levels of the structure.
Global data
Local Data Local Data Local Data Sub-programs
Modules
©Copyright 2004, Cognizant Academy, All Rights Reserved 10
Structured Programming
• Three types of control flow are used:
- sequence
- selection
Y/N
- iteration
©Copyright 2004, Cognizant Academy, All Rights Reserved 11
Structured Programming
• Easy to understand the program, leading to
improved reliability
• Often (but not always) associated with a "top-down"
approach to design
• Lot of dubiousness in this case leaded to evolution
of Object Oriented Programming Paradigm
©Copyright 2004, Cognizant Academy, All Rights Reserved 12
Modular programming
• A software engineering technique (decomposition method)
in which no component in a complex system should depend
on the internal details of any other components (DanIngalls)
• May involve breaking down complex tasks into many
different modules.
• Module – A component of a larger system that operates
within that system independently from the operations of the
other components of the system.
• Ad-hoc method of handling complexity.
©Copyright 2004, Cognizant Academy, All Rights Reserved 13
Functional programming
• Treats computation as the evaluation of mathematical
functions.
• Emphasizes the evaluation of functional expressions,
rather than execution of commands.
• Expressions are formed by using functions to combine
basic values.
• Immutable(inflexible) program rather than modify state
to produce values, constructs state from older pieces
of state in the program.
©Copyright 2004, Cognizant Academy, All Rights Reserved 14
Object Oriented Programming
Program is composed of a collection of individual units, or
objects, as opposed to a traditional view in which a program
is a list of instructions to the computer
Object B
Data variable
Object A Object C
Member Function
Data variable Data variable
Member Function Member Function
©Copyright 2004, Cognizant Academy, All Rights Reserved 15
Object Oriented Programming
• Does not deal with programming in the sense of
developing algorithms or data-structures
• Focuses on ADT
©Copyright 2004, Cognizant Academy, All Rights Reserved 16
POA Vs OOA
Procedure Oriented Approach:
System assembled with the
Director Cell
supplied H/w components
Fetch Components
H/W Components Service Engineer
Send H/w +
Room Room
Instructions to
assemble the
system
©Copyright 2004, Cognizant Academy, All Rights Reserved 17
Object Oriented Approach:
©Copyright 2004, Cognizant Academy, All Rights Reserved 18
Object Oriented Programming
• Does not deal with programming in the sense of developing
algorithms or data-structures, but must be studied as a
(collection of) means for the organization of programs and,
more generally, techniques for designing programs
• Focuses on ADT (Abstract Data Type - a collection of values
and a set of operations on those values, that collection and
those operations from a mathematical construct that may be
implemented using a particular hardware or software data
structure)
©Copyright 2004, Cognizant Academy, All Rights Reserved 19
Programming Paradigms : Summary
• Programming paradigm is a paradigm for programming
computer programs or more generally software or software
systems development.
• Procedural programming - composed of one or more units or
modules-either user coded or provided in a code library.
• Structured programming - a subset or subdiscipline of
procedural programming.
• Modular programming – involves breaking down complex
tasks into many different modules and that is where modular
programming comes into picture.
• Functional programming - treats computation as the
evaluation of mathematical functions.
• Object oriented programming - simulates real world objects.
©Copyright 2004, Cognizant Academy, All Rights Reserved 20
2. Object Oriented Programming Concepts and
C++
Introduction:
In this Module we are going to get an understanding of basic concepts of
Object Oriented Programming.
Objective:
After completing this module, you will be able to understand,
– Class and Object
– Data Abstraction
– Encapsulation
– Inheritance
– Polymorphism
– History of C++
– Attributes of Class
– Object Terminology
– Benefits of OOP
©Copyright 2004, Cognizant Academy, All Rights Reserved 21
Class & Object
Object:
• An Object is a combination of data and behavior.
• Object behavior is referred using terms such as functions,
member functions, methods or operations.
• Data characterizes the state of an object.
Class:
• Description of common properties of objects that belong to
the class i.e., collection of objects with common
characteristics.
• A class does not exist in the memory of computer during
program execution.
• e.g.: Writing material is a class. Pen and Pencil are
objects of the class.
©Copyright 2004, Cognizant Academy, All Rights Reserved 22
Class & Object
Account
acct_no
name
balance
withdraw()
deposit( )
Account:acct1 Account:acct2
431245 431246
Patrick Meyer
50567.78 35567.78
©Copyright 2004, Cognizant Academy, All Rights Reserved 23
What’s Object Oriented programming?
Objects:
• Packaging data and functionality together into units within a
running computer program;
• The basis of modularity and structure in an object-oriented
computer program.
• Self contained and should be easily identifiable.
• In an object-oriented environment, software is a collection
of discrete objects that encapsulate their data as well as the
functionality to model real-world objects.
©Copyright 2004, Cognizant Academy, All Rights Reserved 24
Advantages Of Object Orientation
• Modularity: Since the whole system is being modeled as
classes and various methods are divided according to the
respective functionalities in respective classes modularity
increases.
• Deferred Commitment: Since classes can be modified
without modifying the actual code where the classes are
being used, flexibility towards the commitment increases
(Easier maintenance). The internal workings of an object
can be redefined without changing other parts of the system.
• Reusability: Since defining classes through inheritance
helps in reusability thus faster production.
©Copyright 2004, Cognizant Academy, All Rights Reserved 25
Advantages Of Object Orientation
• Higher Quality: Since deriving classes from existing classes
which are working successfully.
• Reduced cost: Because of reusability
• Increased Scalability: Easier to develop large systems from
well tested smaller systems.
©Copyright 2004, Cognizant Academy, All Rights Reserved 26
Abstraction
"A view of a problem that extracts the essential information
relevant to a particular purpose and ignores the remainder of
the information." - [IEEE, 1983]
• Each object in the system serves as a model of an abstract
"actor" that can perform work, report on and change its state,
and "communicate" with other objects in the system, without
revealing how these features are implemented.
• Denotes the essential characteristics of an object that
distinguishes from all other kinds of objects.
• Focuses on similarities while temporarily ignoring differences.
©Copyright 2004, Cognizant Academy, All Rights Reserved 27
Data Abstraction
Data abstraction is the process of distilling data down to its
essentials, grouping the pieces of data that describe some
entity, so that programmers can manipulate that data as a unit
• Projecting essential features without including the background
details
• Building up data types from the predefined data types is data
abstraction.
• Object-oriented programming can be seen as an attempt to
abstract both data and code.
©Copyright 2004, Cognizant Academy, All Rights Reserved 28
Data Abstraction
Kinds of data abstraction :
Association - A relationship between two classes that
represents the existence of a set of links between objects of
the two classes
• Attribute - A simple data item present in all the instances of a
class
• Class - A software module that provides both procedural and
data abstraction. It describes a set of similar objects, called
its instances
• Data type - A name or label for a set of values and some
operations which one can perform on that set of values.
©Copyright 2004, Cognizant Academy, All Rights Reserved 29
Encapsulation
• Bundling of the data and methods together
• Ensuring that users of an object cannot change the internal
state of the object in unexpected ways; only the object's
own internal methods are allowed to access its state.
• Each object exposes an interface that specifies how other
objects may interact with it. Other objects will rely
exclusively on the object's external interface to interact with
it.
©Copyright 2004, Cognizant Academy, All Rights Reserved 30
Information Hiding
"The process of hiding all the details of an object that do not
contribute to its essential characteristics; typically, the
structure of an object is hidden, as well as the
implementation of its methods. The terms information
hiding and encapsulation are usually interchangeable."
- [Booch, 1991]
• Hiding all the details of an object that does not contribute to
its essential characteristics.
• Why is it needed? ( We separate the implementation details
from the actual use )
©Copyright 2004, Cognizant Academy, All Rights Reserved 31
Inheritance
• Inheritance is a way to form new classes using classes that
have already been defined.
• The former, known as derived classes, take over (or
inherit) attributes and behavior of the latter, which are
referred to as base classes.
• It is intended to help reuse of existing code with little or no
modification.
©Copyright 2004, Cognizant Academy, All Rights Reserved 32
Inheritance
Account
acct_no
name
balance
withdraw()
deposit( )
Savings Acc Current Acc
interest overdraft
©Copyright 2004, Cognizant Academy, All Rights Reserved 33
Polymorphism
• It is using the same name to invoke different operations on
objects of different data types.
• Idea of allowing the same code to be used with different
types, resulting in more general and abstract
implementations.
• It refers to the ability of an object to behave in different ways
based on the context.
• Single message interpreted by different objects in different
way.
©Copyright 2004, Cognizant Academy, All Rights Reserved 34
C++: The History
• Bjarne Stroustrup developed C++ (originally named "C
with Classes") during the 1980s.
• The name C++ was coined by Rick Mascitti in 1983.
• Standard was ratified in 1998 as ISO/IEC 14882:1998
• New version of the standard (known informally as
C++0x) is being developed.
©Copyright 2004, Cognizant Academy, All Rights Reserved 35
Attributes of Class
Member variables:
State or properties of an object of that class.
Various variables that are defined in the class
They are attributes of an object.
class Point { … … ;};
class StraightLine {
// object’s attributes
Point &StartPoint, &Endpoint; //Reference data member
int Color; //Non-static data member
const int Thickness; //Constant data member
// class’ attributes
static int NoOfLineObjects; //Static data member
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 36
Attributes of Class
Member functions:
They are actions that object can do.
Used to access data inside the class.
They are handles to the outside world and other objects.
Constructors - memory allocation, initialization for data
Destructors - freeing the memory
Static functions - class oriented, modify only static data
Non-static ” - object oriented
Const functions - cannot modify data member’s values
Virtual functions - help dynamic binding of function calls to
implementation
©Copyright 2004, Cognizant Academy, All Rights Reserved 37
Attributes of Class
Access modifiers:
Members can be declared
Private
visible only inside the class
Protected
private + visible to the immediately derived class
Public
globally visible
©Copyright 2004, Cognizant Academy, All Rights Reserved 38
Attributes of Class
Scope Resolution Operator ( :: )
Unary scope resolution operator
Hidden global variables can be accessed
Hidden local variables cannot be accessed
int a=10;
void main () {
int a=20;
{
int a=30;
cout<<”local a=”<< a; //30
cout<<”hidden global a=”<< ::a; //10;
}
cout<<“hidden local a=“<<a; //20;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 39
Attributes of Class
Binary scope resolution operator
class HelloWorldCls {
public: void displayHelloWorld();
};
void HelloWorldCls :: displayHelloWorld() // Binary
{ cout<<” This is member function”; }
void displayHelloWorld() // global function
{ cout<<”This is global function”; }
void main(void)
{ HelloWorldCls hwObj;
hwObj.displayHelloWorld( ); // Member function call
displayHelloWorld( ); // Global function call
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 40
OOP Concepts: Summary
• In an object –oriented environment, software is a collection
of discrete objects that encapsulate their data as well as the
functionality to model real-world objects.
• Object orientation mainly Promotes of reusability.
• The main advantage of an OO system is that the class tree
is dynamic and can grow.
• Data abstraction is the enforcement of a clear separation
between the abstract properties of a data type and the
concrete details of its implementation.
©Copyright 2004, Cognizant Academy, All Rights Reserved 41
Functions in C++
• References
• Function Overloading
• Default values
• Inline Functions
• Function Templates
• Friend Functions
• Static Members and Functions
• Constant Functions and Constant data members
©Copyright 2004, Cognizant Academy, All Rights Reserved 42
Parameter passing mechanisms
• Call by Value:
void swap (int, int); //prototype
main( )
{
int x=4,y=5;
cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5
swap (x, y); //x, y actual args
cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5
}
void swap (int a, int b) //a, b formal args
{
int k;
k=a; a=b; b=k;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 43
Parameter passing mechanisms
• Call by value: another example
main( )
{
int x,y; //actual args x y
void change(int,int); 4 5
x=4; y=5;
change(x, y);
}
void change(int a, int b)
a b
{ //a,b formal args
int k; 5 4
k=a; a=b; b=k;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 44
Parameter passing mechanisms
• Call by Address:
void swap (int*, int*); //prototype
main( )
{
int x=4,y=5;
cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5
swap (&x, &y);
cout<<“x=“<<x<<“ y=“<<y; output: x=5 y=4
}
void swap (int* a, int* b)
{
int k;
k=*a; *a=*b; *b=k;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 45
Parameter passing mechanisms
• Call by address: another example
main( )
{
int x,y; //actual args x y
void change(int *,int*); 4 5
x=4; y=5;
change(&x, &y); )
} = 4 ge(
y an
c h
= 5 g
X ll i n
void change(int *a, int *b) c a
r
{ //a,b formal args tf e
A
int *k;
*k=*a; *a=*b; *b=*k;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 46
Parameter passing mechanisms
• Call by Reference:
void swap (int&, int&); //prototype
main( )
{
int x=4,y=5;
cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5
swap (x, y);
cout<<“x=“<<x<<“ y=“<<y; output: x=5 y=4
}
void swap (int &a, int &b)
{
int k;
k=a; a=b; b=k;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 47
References
• Not a copy of the variable and cannot exist without a
variable to refer to it.
• Cannot be manipulated independently.
• Can be viewed as pointers without dereferencing
notation.
int actualint = 123;
int *const intptr = &actualint;
Const pointer – Initialized to actualint
cannot point to another variable
©Copyright 2004, Cognizant Academy, All Rights Reserved 48
References & Constants
• Value of a reference cannot be changed
actualint otherint
int actualint = 123;
int &otherint = actualint;
otherint++
123
otherint++
124
int & const otherint = actualint; // Error
Meaningless as all references are constants
by definition
©Copyright 2004, Cognizant Academy, All Rights Reserved 49
References
• Reference
• Creates a alternate name or alias for the variable
• Used to read or modify the original data stored in that
variable
• Syntax of reference variable declaration:
Standard or user defined data type: char, short, int, float, etc.
Reference operator
C++ alias variable
C++ value variable
DataType & ReferenceVariable = ValueVariable
©Copyright 2004, Cognizant Academy, All Rights Reserved 50
References
int count = 1; // declare integer variable count
int &ref = count; // create ref as an alias for count
++ref; // increment count (using its alias)
count
count
1
2
ref
ref
©Copyright 2004, Cognizant Academy, All Rights Reserved 51
References and pointers
• Reference to a constant:
Possible int actualint = 123;
const int &otherint = actualint;
•readonly alias for actualint
•can’t make any modification
• Constant reference
declaration: int & const otherint = actualint;
Not Possible // Error
• Meaningless as all references
are constants by definition
©Copyright 2004, Cognizant Academy, All Rights Reserved 52
Function Overloading
• Having more than one function with the same name
differing in number of arguments or type of
arguments.
• It is a kind of Compile time Polymorphism (dealt
later)
Issues in Function Overloading
• Functions differing in their return types only cannot
be overloaded.
©Copyright 2004, Cognizant Academy, All Rights Reserved 53
Function Overloading
• Passing constant values directly can also lead to
ambiguity as internal type conversions may take
place.
Consider: sum(int,int) and sum(float,float,float)
The compiler will not be able to distinguish between
the two calls made below
sum(2,3) and sum(1.1, 2.2, 3.3)
©Copyright 2004, Cognizant Academy, All Rights Reserved 54
Function Overloading
Example:
Convert function to convert a float Fahrenheit temperature to
Celsius
• Prototype (Declaration):
void ConvertFToC(float f, float &c);
• Definition:
void ConvertFToC(float f, float &c)
{
c = (f - 32.) * 5./9.;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 55
Function Overloading
If Convert function is also needed to convert an
integer Fahrenheit temperature to Celsius in the
same program:
- give this function a new name, and update the
name of the
"float" version as well.
void fConvertFToC(float f, float &c);
void iConvertFToC(int f, int &c);
©Copyright 2004, Cognizant Academy, All Rights Reserved 56
Function Overloading
• The compiler attempts to find an accurate function
definition that matches in types and number of
arguments and invokes the function.
• If no accurate match found,
– compiler tries out implicit conversions.
E.g., char is converted to int, float to double etc.
©Copyright 2004, Cognizant Academy, All Rights Reserved 57
Default Values
• Function arguments assume default values, when their
values are neglected or insufficient number of values are
furnished during function calls.
• Can be constants, global variables, or function calls
• Sets defaults in function prototype
int myFunction(int x = 1,int y = 2,int z = 3)
myFunction(3)
x = 3, y and z get defaults (rightmost)
myFunction(3, 5)
x = 3, y = 5 and z gets default
©Copyright 2004, Cognizant Academy, All Rights Reserved 58
Default Values
• Examples:
// Declarations //Function calls
int add(int a, int b); // prototype 1 cout<<add(15,10);
int add(int a, int b, int c); // prototype 2 cout<<add(15,10.5);
double add(double x, double y) // prototype 3 cout<<add(15.5,10.5);
double add(int p, double q) // prototype 5 cout<<add(15,10,5);
double add(double p,int q) // prototype 5 cout<<add(0.15,1.05);
©Copyright 2004, Cognizant Academy, All Rights Reserved 59
Default Values
Basic rules:
• When a default is provided, all remaining
parameters must be given defaults.
• Default values must be of the correct type.
• Defaults can be placed on the function prototype or
the function definition from right to left.
©Copyright 2004, Cognizant Academy, All Rights Reserved 60
Inline Functions
• Eliminates the function-call overhead (caused by
jumping in and out of functions having few
statements) involved in the conventional functioning
approach.
– Keyword inline before function
– Asks the compiler to copy code into program
instead of making function call
– Compiler can ignore inline
– Good for small, often-used functions
©Copyright 2004, Cognizant Academy, All Rights Reserved 61
Inline Functions
Syntax of inline function definition:
Keyword, function qualifier
inline ReturnType FunctionName(Parameters)
{
// Body of a main function
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 62
Inline Functions
inline int sqr(int num)
{ return num * num; }
void main( ) void main( )
preprocessor
{ --- { ---
a=sqr(5); a = 5 * 5;
b=sqr(n); b = n * n;
--- ---
} }
• If a member function is implemented outside the
class braces, it is not inline by default, but it can be
defined as inline using the inline keyword.
©Copyright 2004, Cognizant Academy, All Rights Reserved 63
Inline Functions versus Macros
Inline functions: parsed by the compiler
Macros : expanded by the preprocessor.
E.g., #define max(x,y) ((x>y)?x: y)
Limitation with macro:
Macros are not functions and errors are not
checked at compilation time.
©Copyright 2004, Cognizant Academy, All Rights Reserved 64
Inline Functions versus Macros
Reasons why Inline functions are better than macros:
• Follow all the protocols of type safety enforced on
normal functions.
• Specified using the same syntax as any other
function except that they include the inline
keyword in the function declaration.
• Expressions passed as arguments to inline
functions are evaluated once. In some cases,
expressions passed as arguments to macros can
be evaluated more than once.
©Copyright 2004, Cognizant Academy, All Rights Reserved 65
Inline Functions versus Macros
# define SQUARE(num) num * num
Output r =25 s =16
inline float square(float j)
{
return (j * j);
}
Macro SQUARE( ) expands into
void main( ) r = ++num * ++num
{ int p=3,q=3,r,s; In macro expansion
r=SQUARE(++p); num is incremented twice.
s=square(++q);
cout<<“r = “ << r << “s = “<<s; Inline function square( )
} var ‘q’ is incremented only
once and is assigned to j
then j * j.
©Copyright 2004, Cognizant Academy, All Rights Reserved 66
Static Data Members and Member Functions
• Static members are members that are single shared member
common to all the objects created for a particular class.
• Memory allocation is done only once and not every time an
object is created.
• Static functions can access only static variables
• Efficient when single copy of data is enough
• May seem like global variables, but have class scope
• Only accessible to objects of same class
©Copyright 2004, Cognizant Academy, All Rights Reserved 67
Static Members contd.,
• Static Data Members:
Object A
Object B Static variable
Object C
©Copyright 2004, Cognizant Academy, All Rights Reserved 68
Static Members contd.,
• Static Member Example
class account {
private:
int currentBal;
static int RateofInt; Shared by
}; all objects
myclass A(0), B(1);
Object
Ra
te B
of
In
t
Object A
currentBal=0 currentBal=1
©Copyright 2004, Cognizant Academy, All Rights Reserved 69
Static Members contd.,
• Static Data Members:
class SavingsAccount Only one copy should
{ be available as all
private: objects should have
char name[30]; same Interest rate
float total;
float CurrentRate;
public: To make CurrentRate
SavingsAccount(); accessible to all objects
void EarnInterest()
{ Declare CurrentRate as
total + = CurrentRate * total;
} static float CurrentRate;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 70
Constant data member and Constant Functions
• A constant variable can be declared using const
keyword
• Compiler error results if attempted to modify it
Syntax:
const <variable-name> = <value>
Example: const int age = 20;
const int age; // Not valid
©Copyright 2004, Cognizant Academy, All Rights Reserved 71
Constant data member and Constant Functions
• The const keyword specifies that a variable's value is
constant and tells the compiler to prevent the programmer
from modifying it. int main()
{
const int i = 5;
---
}
• Declaring a member function with the const keyword
specifies that the function is a "read-only" function that does
not modify the object for which it is called.
• If a const function attempt to change the data, the compiler
will generate an error message.
©Copyright 2004, Cognizant Academy, All Rights Reserved 72
Constant data member and Constant Functions
• Illegal to declare a const member function that
modifies a data member
• For built-in types it doesn’t matter whether we return
by value as a const
int fun1( ) {return 1;}
int fun2( ) const {return 1;}
main( )
{
const int i = fun1( );
int j = fun2( );
---
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 73
Constant data member and Constant Functions
class Time
{
int hour;
public:
Time(int k) { hour=k; }
void update( ) { hour++; }
int value( ) const { return hour; }
void cheat( ) const { hour++; } // error this is const
};
void main (void)
{
Time t(10);
cout<<t.value( ); 11
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 74
Function Templates
• To create generic functions that admit any data type
as parameters and return a value without having to
overload the function with all the possible data
types.
• Until certain point they fulfill the functionality of a
macro.
• Compact way to make overloaded functions
• Generate separate functions for different data types.
©Copyright 2004, Cognizant Academy, All Rights Reserved 75
Function Templates
Keyword for declaring function template
Keyword class
Name of the template data-type
Function parameters of type
template, primitive or user-defined
template < class identifier >
ReturnType FunctionName(arguments of type identifier)
template < class T > // or template< typename T >
T square( T value1 )
{
return value1 * value1;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 76
Function Templates
Examples:
Convert function to convert a float Fahrenheit temperature to
Celsius
Prototype (Declaration):
template <class Type>
void ConvertFToC(Type f, Type &c);
Definition:
template <class Type>
void ConvertFToC(Type f, Type &c)
{
c = (f - 32.) * 5./9.;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 77
Function Templates
efinition of function template maximum In main( )
plate < class T > maximum( int1, int2, int3 )
// or template < typename T >
aximum( T value1, T value2, T value3 )
T max = value1; maximum( double1, double2, double3 )
if ( value2 > max )
max = value2;
if ( value3 > max )
max = value3; maximum( char1, char2, char3 )
return max;
Output
Input values Maximum value
1, 2, 3 3
1.1 , 2.1, 1.8 2.1
A, B,C C
©Copyright 2004, Cognizant Academy, All Rights Reserved 78
Function Template Overloading
• Other function templates with same name
– Different parameters
• Non-template functions with same name
– Different function arguments
• Compiler performs matching process
– Tries to find precise match of function name
and argument types
– If fails, function template generates function-
template specialization with precise match
©Copyright 2004, Cognizant Academy, All Rights Reserved 79
3. Classes and Objects
Objective:
After completing this module, you will be able to understand,
– Constructors
– Destructors
– Copy Constructors
– Constant Object
– Static Object
– Friend Class
– Template Class
©Copyright 2004, Cognizant Academy, All Rights Reserved 80
Constructors
Introduction:
• Constructors are special member functions with the
same name as the class.
• A constructor initializes each object when it is
created
• They are commonly used to initialize the member
variables.
©Copyright 2004, Cognizant Academy, All Rights Reserved 81
Constructors contd.,
• Constructors do not return values.
• A constructor is called whenever an object is
defined or dynamically allocated using the “new”
operator
• If no constructor is explicitly written then a default is
created (not in the case of const and reference data
members).
©Copyright 2004, Cognizant Academy, All Rights Reserved 82
Constructors contd.,
class sum
{ Constructor declared
public:
int x, y;
sum( ); Constructor defined
};
sum::sum(void) Object created and
{ initialized by
cout<<" Inside sum( )\n"; constructor
x=2;y=4; // if not initialized garbage
} Inside sum( )
void main( ) Inside main( )
{ x= 2 y= 4
sum s;
cout<<"Inside main( )\n";
cout<<"x= " << s.x<<"y= "<<s.y;
} Object s x= 2
y= 4
©Copyright 2004, Cognizant Academy, All Rights Reserved 83
Constructors with arguments
• Parameters can be passed to the constructors
class sum
{
Parameterized Constructor
public:
int x, y;
sum(int i,int j);
};
sum::sum(int i,int j) Constructor called implicitly
{
x=i;y=j;
}
void main( )
{
sum s1(10,20);
Object s1 x= 10 y= 20
sum s2 = sum(30,40);
cout<<"x= " << s1.x<<"y= "<<s1.y;
cout<<"x= " << s2.x<<"y= "<<s2.y; Object s2 x= 30 y= 40
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 84
Overloading Constructors
• Overloading Constructors - Multiple constructors
declared in a class
• All constructors have different number of arguments
• Depending on the number of arguments, compiler
executes corresponding constructor
sum( ) {x=10;y=20;}; No arguments
sum(int, int) {x=i;y=j;}; Two arguments
sum(sum & i) {x=i.x;y=i.y;}; Copy constructor
©Copyright 2004, Cognizant Academy, All Rights Reserved 85
Constructors with default arguments
• Constructors can be defined with default arguments
class sum Object s1 x= 1 y= 10
{
public: int x, y;
sum(int i, int j=10); Object s2 x= 8 y= 9
};
sum::sum(int i,int j)
Default value for
{x=i;y=j;}
j=10 (Used by the
void main()
object s1)
{
sum s1(1),s2(8,9);
cout<<"\nx in s1= " << s1.x<<"y in s1= "<<s1.y;
cout<<"\nx in s2= " << s2.x<<"y in s2= "<<s2.y;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 86
Copy Constructors
• C++ calls a copy constructor to make a copy of an object.
• If there is no copy constructor defined for the class, C++ uses
the default copy constructor which copies each field, ie,
makes a shallow copy.
• Constructors can accept arguments of any data type
including user defined data types and an object of its own
class
sum s1(10); //Object created and initialized
sum s2(s1); //Copy constructor
sum s3=s1; //Copy constructor
sum s4;
s4=s1; //Assignment
©Copyright 2004, Cognizant Academy, All Rights Reserved 87
Copy Constructors contd.,
class sum
void main()
{ {
public: sum s1(10);
int x; sum s2(s1);
sum(){ } sum s3=s1;
sum(int i) {x=i;} sum s4;
sum(sum &j) {x=j.x;} s4=s1;
}; cout<<"\nx in s1= " << s1.x;
cout<<"\nx in s2= " << s2.x;
cout<<"\nx in s3= " << s3.x;
cout<<"\nx in s4= " << s4.x;
}
Objects s1 s2 s3 s4
x=10 x=10 x=10 x=10
©Copyright 2004, Cognizant Academy, All Rights Reserved 88
Copy Constructors contd.,
#include<string.h>
class String
int main()
{
{
char* data; String s = "hello"; // same as String s("hello");
public: cout <<”s=”<<s.display( );
String(const char* s = "") String empty;
{ cout<<”empty=”<<empty.display();
data = new char[20]; }
strcpy(data,s);
}
~String() {delete [] data;}
int size() const {return strlen(data);}
void assign(char str*)
{ strcpy(data,str);
void display()
{ s = hello
cout << data;
}
empty=
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 89
Copy Constructors contd.,
int main()
{ hello
String s = "hello"; hello
String t = s; // same as String t(s); world
s.display( ); world
t.display( );
t.assign(“world”);
s.display( );
t.display( );
} Shallow Copy
data
hello\0
data
©Copyright 2004, Cognizant Academy, All Rights Reserved 90
Copy Constructors contd.,
String(const String& s)
{
data = new char[strlen(s.data)+1];
strcpy(data, s.data);
} Deep Copy
data hello\0
Deep copy
data
hello\0
©Copyright 2004, Cognizant Academy, All Rights Reserved 91
Destructors
• When an object goes out of scope then it is
automatically destructed.
• It performs clean up of the object ( in the case of
allocating memory inside the object using new )
• Destructors have no arguments and thus cannot be
overloaded
©Copyright 2004, Cognizant Academy, All Rights Reserved 92
Destructors contd.,
Declaration
– Same name as class
• Preceded with tilde (~)
~sum( ) { }
©Copyright 2004, Cognizant Academy, All Rights Reserved 93
Constant Objects
const objects using const keyword before object
declaration.
For example:
const sample s ( m, n); // object s is constant
©Copyright 2004, Cognizant Academy, All Rights Reserved 94
Static Object
• When an object is created as static, the lifetime of
the object will exist throughout the program
• Execution and scope of the instance will also be
maintained.
©Copyright 2004, Cognizant Academy, All Rights Reserved 95
Static Object Example
#include<iostream.h>
class account
{ int acc_no; Account constructor
public: Account constructor
account() Account destructor
{cout<<"Account constructor"; }
~account()
{cout<<"Account desctructor"; }
};
void create_stobj()
{ account vip;
}
void main(void) sta
{ tic
acc
clrscr(); oun
account acc1; t vi
p;
create_stobj(); Account constructor
getch(); Account constructor
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 96
Friend class
• Like friend function, there is also a provision in C++
for having friend classes.
• Here an entire class is declared as friend for
another class.
• When a class is declared as friend, it means the
members of the friend class have access to all the
public and private members of the class in which
the declaration was made.
©Copyright 2004, Cognizant Academy, All Rights Reserved 97
Friend class example
#include <iostream.h>
class two class one
{ int a1,b1;
int a,b; public:
public: one(void)
void let(int x, int y) { a1=5, b1=10;
{ a=x; b=y; } }
void print(void) friend class two;
{cout<<"a="<<a<<" b="<<b; } };
void assign(one x) void main(void)
{ { one o1;
a=x.a1; two t1;
b=x.b1; t1.let(4,2);
} t1.print();
}; t1.assign(o1);
t1.print(); a = 4 b= 2
} a= 5 b=10
©Copyright 2004, Cognizant Academy, All Rights Reserved 98
Template class
#include<iostream.h>
Template < class Image>
Class generic
{
Image t;
public:
void sum(Image x, Image y)
{ t= x+ y; }
void print (void)
{ cout<< “ The sum is : “ << t <<”\n”; }
};
main ( )
{ generic <int> x;
generic <float> y;
x.sum(5,1);
x.print( );
The sum is : 5
y.sum(2.2, 3.7); The sum is : 5.9
y.print( ); }
©Copyright 2004, Cognizant Academy, All Rights Reserved 99
4. Inheritance
• By using the concepts of inheritance, it is possible
to create a new class from an existing one and add
new features to it.
• Inheritance provides a mechanism for class level
Reusability.
• Semantically, inheritance denotes an “is-a”
relationship.
©Copyright 2004, Cognizant Academy, All Rights Reserved 100
Inheritance
• Inheritance is the relationship between a class and
one or more refined version of it.
• The class being refined is called the superclass or
base class and each refined version is called a
subclass or derived class.
• Attributes and operations common to a group of
subclasses are attached to the superclass and
shared by each subclass.
• Each subclass is said to inherit the features of its
superclass.
©Copyright 2004, Cognizant Academy, All Rights Reserved 101
Inheritance
Person
Name
Sex
Age
Student Teaching Staff
Reg.No. Edn.Qual.
Course Designation
Marks Specialization
“Person” is a generalization of “Student”.
“Student” is a specialization of “Person”.
©Copyright 2004, Cognizant Academy, All Rights Reserved 102
Defining Derived Class
• The general form of deriving a subclass from a base class is
as follows
Class derived-class-name : visibility-mode base-class-name
{
……………… //
……………….// members of the derived class
};
• The visibility-mode is optional.
• It may be either private or public or protected, by default it is
private.
• This visibility mode specifies how the features of base class
are visible to the derived class.
©Copyright 2004, Cognizant Academy, All Rights Reserved 103
Inheritance
Types of Inheritance
• Inheritance are of the following types
• Simple or Single Inheritance
• Multi level or Varied Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
• Virtual Inheritance
©Copyright 2004, Cognizant Academy, All Rights Reserved 104
Simple or Single Inheritance
• This a process in which a sub class is derived from only one
superclass.
• a Class Student is derived from a Class Person
class Person
Person superclass(base class)
{ ….. };
class Student : public Person
{
Student subclass(derived class) …………
};
visibility mode
©Copyright 2004, Cognizant Academy, All Rights Reserved 105
Multilevel or Varied Inheritance
• The method of deriving a class from another derived class is
known as Multiple or Varied Inheritance.
• A derived class CS-Student is derived from another derived
class Student.
Person
Class Person
{ ……};
Student Class Student : public Person
{ ……};
Class CS -Student : public Student
CS -Student { …….};
©Copyright 2004, Cognizant Academy, All Rights Reserved 106
Multiple Inheritance
• A class is inheriting features from more than one super
class
• Class Part-time Student is derived from two base classes,
Employee and Student
Employee Student Class Employee
{……..};
Class Student
{……..};
Class Part-time Student : public Employee,
Part-time Student public Student
{…….};
©Copyright 2004, Cognizant Academy, All Rights Reserved 107
Hierarchical Inheritance
• Many sub classes are derived from a single base class
• The two derived classes namely Student and Employee are
derived from a base class Person.
Class Person
Person {……};
Class Student : public Person
{……};
Class Employee : public Person
Student Employee
{……};
©Copyright 2004, Cognizant Academy, All Rights Reserved 108
Hybrid Inheritance
• In this type, more than one type of inheritance are used to
derive a new sub class
• Multiple and multilevel type of inheritances are used to
derive a class PG-Student
Person
Class Person
{ ……};
Class Student : public Person
{ ……};
Student Gate Score Class Gate Score
{…….};
Class PG - Student : public Student
public Gate Score
PG - Student {………};
©Copyright 2004, Cognizant Academy, All Rights Reserved 109
Virtual Inheritance
• A sub class is derived from two super classes which
in-turn have been derived from another class.
• The class Part-Time Student is derived from two
super classes namely, Student and Employee.
• These classes in-turn derived from a common super
class Person.
• The class Part-time Student inherits, the features of
Person Class via two separate paths
©Copyright 2004, Cognizant Academy, All Rights Reserved 110
Virtual Inheritance
Person
Student Employee
Class Person
{……};
Part-time Student Class Student : public Person
{……};
Class Employee : public Person
{……};
Class Part-time Student : public Student,
public Employee
{…….};
©Copyright 2004, Cognizant Academy, All Rights Reserved 111
Inheritance cont’d…,
Four things you might find in an Inheritance Hierarchy
– Super class is too general to declare all behavior, so each
subclass adds its own behavior.
– Super class legislates an abstract behavior and therefore
delegates implementation to sub class.
– Super class specifies behavior, subclasses inherit
behavior.
– Super class specifies behavior, subclasses choose to
override behavior.
©Copyright 2004, Cognizant Academy, All Rights Reserved 112
Access Control
• A member of a class can be private, public. In inheritance,
we are going to use another access specify namely
protected. So, a member of a class can be private,
protected, or public.
• If a member of a class is private, its name can be used only
by member functions and friends of the class in which it is
declared.
• If it is protected, its name can be used only by member
functions and friends of the class in which it is declared and
by member functions and friends of classes derived from this
class.
• If it is public, its name can be used by any function.
©Copyright 2004, Cognizant Academy, All Rights Reserved 113
Access Specifiers with Inheritance
• If we want an instance variable to be available for
subclasses to change it, then we can choose
access specifier protected.
• The following example illustrates the usage of these
access specifiers.
©Copyright 2004, Cognizant Academy, All Rights Reserved 114
Access Specifiers with Inheritance
Class X Y::mderived( )
{ {
int priv; priv =1; //Error priv is private and
protected: //cannot be inherited
int prot; prot =2; // Ok
public: publ=3; // Ok
int publ; }
void m( ); void global_fun(Y *p)
}; {
void X::m( ) p->priv = 1; //Error : priv is
{ //private of X
priv =1; //Ok p->prot = 2; //Error : prot is
prot =1; //Ok //protected and the function global_fun( )
publ =1; //Ok // is not a friend or a member of X or Y
} p->publ =3; // Ok
class Y : public X }
{ void mderived( ); }
©Copyright 2004, Cognizant Academy, All Rights Reserved 115
Public, Protected and Private derivation
Class A Class B Class B: Public A
private : private : private :
int a1; int b1; int b1;
protected : protected : protected:
int a2; int b2; int a2;
int b2
public : public : public:
int a3; int b3; int b3;int a3;
Public Derivation
©Copyright 2004, Cognizant Academy, All Rights Reserved 116
Public derivation - example
class A
{ void main( )
private : int a; {
protected: int b; B b1;
public : void get_a( ) { cin>>a;} b1.get_a( );
void get_b( ) { cin>>b;} b1.get_b( );
void print_a( ) { cout<<a;} b1.get_c( );
void print_b( ) {cout<<b;} b1.get_d( );
}; b1.print_all( );
class B : public A }
{
private : int c;
protected: int d;
public : void get_c( ) { cin>>c;}
void get_d( ) {cin >>d;}
void get_all( ) { get_a( ); cin>>b>>c>>d;}
void print_cd( ){ cout<<c<<d;}
void print_all( ) { print_a( ); cout<<b<<c<<d; }
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 117
Protected derivation - example
• The inherited public and protected members of a base class
become protected members of the derived class
Class A Class B Class B : Protected A
private : private : private :
int a1; int b1; int b1;
protected:
protected : protected :
int a2;
int a2; int b2;
int b2,a3;
public : public : public:
int a3; int b3; int b3;
Protected Derivation
©Copyright 2004, Cognizant Academy, All Rights Reserved 118
Protected derivation - example
class A
{ void main( )
private: int a; {
protected: int b; B b1;
public : void get_a( ) { cin>>a;} b1.get_a( ); //ERROR
void get_b( ) { cin>>b;} b1.get_b( ); //ERROR
void print_a( ) { cout<<a;} b1.get_ab( );
void print_b( ) {cout<<b;} b1.get_c( );
}; b1.get_d( );
class B : protected A b1.print_all( );
{ private : int c; }
protected: int d;
public : void get_c( ) { cin>>c;}
void get_d( ) {cin >>d;}
void get_ab( ) { get_a( ); get_b( );}
void print_cd( ){ cout<<c<<d;}
void print_all( ) { print_a( );
cout<<b<<c<<d;};
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 119
Private derivation - example
The inherited public and protected members of a private
derivation become private members of the derived class.
Class A Class B Class B : private A
private : private : private :
int a1; int b1; int b1;
int a2,a3;
protected : protected :
int a2; int b2; protected:
int b2;
public : public :
int a3; public:
int b3;
int b3;
Private Derivation
©Copyright 2004, Cognizant Academy, All Rights Reserved 120
Private derivation - example
class A Class C : public B
{ { public :
private: int a; void get_all( )
protected: int b; { get_a( ); //ERROR
public : void get_a( ) { cin>>a;} get_b( ); //ERROR
void get_b( ) { cin>>b;}
get_ab( ); //Ok
void print_a( ) { cout<<a;}
get_c( ); //Ok
void print_b( ) {cout<<b;}
get_d( ); //Ok }
};
void print_all( )
class B : private A
{ print_a( ); //ERROR
{
print_b( ); //ERROR
private : int c;
print_cd( ); //Ok
protected: int d;
print_abcd( ); //Ok } };
public : void get_c( ) { cin>>c;}
void main( )
void get_d( ) {cin >>d;}
{ C c1;
void get_ab( ) { get_a( ); get_b( );}
c1.get_a( ); //ERROR
void print_cd( ){ cout<<c<<d;}
c1.get_b( ); //ERROR
void print_abcd( ) { print_a( );
cout<<b<<c<<d; } c1.get_c( ); // Ok
}; c1.get_d( ); //Ok
c1.getall( ); //Ok
c1.print_all( ); //Ok }
©Copyright 2004, Cognizant Academy, All Rights Reserved 121
Derived Class Constructors
• A base class constructor is invoked(if any) , when a
derived class object is created.
• If base class constructor contains default
constructor, then the derived class constructor need
not send arguments to base class constructors
explicitly.
• If a derived class has constructor, but base class
has no constructor, then the appropriate derived
class constructor executed automatically whenever
a derived class object is created.
©Copyright 2004, Cognizant Academy, All Rights Reserved 122
Derived Class Constructors
class B
{
int x;
public :
B( ) { cout<<”B::B( ) Fires…”<<endl;}
};
class D : public B
{ B::B( ) Fires…
int y; D::D( ) Fires…
public :
D( ) { cout<<”D::D( ) Fires…”<<endl;}
};
void main( )
{
D d;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 123
Derived Class Constructors
class B
{
int a;
public :
B( ) { a = 0; cout<<”B::B( ) Fires…”<<endl;}
B(int x) { a =x; cout<<”B::B(int) Fires…”<<endl;}
};
class D : public B
{ int b; B::B( ) Fires…
public : D::D( ) Fires…
D( ) { b =0; cout<<”D::D( ) Fires…”<<endl;} B::B( ) Fires…
D::D(int) Fires…
D(int x) { b =x; cout<<”D::D(int) Fires…”<<endl;} B::B(int) Fires…
D(int x, int y) : B(y) D::D(int, int) Fires…
{ b =x; cout<<”D::D(int, int) Fires…”<<endl;}
};
void main( )
{
D d;
D d(10);
D d(10, 20);
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 124
Derived Class Destructors
• Derived class destructors are called before base class destructors.
class B
{
int x;
public :
B( ) { cout<<”B Constructor Invoked…”<<endl;}
~B( ) { cout<<”B Destructor Invoked …”<<endl;}
}; B Constructor Invoked…
class D : public B D Constructor Invoked…
{ D Destructor Invoked…
int y; B Destructor Invoked …
public :
D( ) { cout<<”D Constructor Invoked …”<<endl;}
~ D( ) { cout<<”D Destructor Invoked…”<<endl;}
};
void main( )
{ D d; }
©Copyright 2004, Cognizant Academy, All Rights Reserved 125
Overriding Member Functions
• When the same function exists in both the base class and the
derived class, the function in the derived class is executed
class A void main( )
{ {
protected : int a;
public : B b1;
void getdata( ) { cin>>a;} b1.getdata( ); // B::getdata( )
void putdata( ) { cout << a;} //is invoked
}; b1.putdata( ); // B::putdata( )
class B : public A //is invoked
{ b1.A::getdata( ); // A::getdata( )
protected: int b; // is invoked
public : void getdata( ) b1.A::putdata( ); // A::putdata( )
{ cin>>a>>b;} //is invoked
void putdata( ) { cout<<a<<b;} }
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 126
Composition
• Classes having objects of other classes as their data
members - composite classes class y
{
int i;
public:
X x;
Y()
class x { i=0;}
{ int i; void f(intj)
public: { i=j;}
x() int g() const
{i=0;} { return i;}
void set(int j) };
{ i=j;} int main()
int read() const { Y y;
{ return i;} y.f(5);
}; y.x.set(10);
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 127
SUMMARY
• A subclass may be derived from a class and inherit its methods and
members.
• Different types are
Single inheritance
Multiple inheritance
Multilevel inheritance
• Base class constructors are also executed whenever derived class objects
created.
• Derived class can override a member function of a base class.
©Copyright 2004, Cognizant Academy, All Rights Reserved 128
5. Polymorphism
Introduction:
In this Module one of the most important concept of OOPS
i.e Polymorphism is discussed.
Objective:
– After completing this module,you will be able to
understand,
– Static Polymorphism
– Overloaded Functions
– Overloaded Operators
– Dynamic Polymorphism
– Virtual Functions
©Copyright 2004, Cognizant Academy, All Rights Reserved 129
Polymorphism
• Greek word meaning - many or multiple
forms.
• In programming languages, polymorphism
means that some code or operations or
objects behave differently in different contexts
• It provides a single interface to entities of
different types.
©Copyright 2004, Cognizant Academy, All Rights Reserved 130
Types of polymorphism
Polymorphism
Static Dynamic
Polymorphism Polymorphism
Function Operator Virtual Fucntion
Overloading Overloading
©Copyright 2004, Cognizant Academy, All Rights Reserved 131
Polymorphism
• Compiler determines a location in memory is called binding
• Connecting a function call to a function body is called
Binding
• The location may represent the following
– Variable names bound to their storage memory address
(offset)
– Function names bound to their starting memory address
(offset)
• Two kinds of binding
• Compile-Time Binding
• Run-Time Binding
©Copyright 2004, Cognizant Academy, All Rights Reserved 132
Static Polymorphism
• Compile-time binding or early binding is called as static
polymorphism.
• Compile-Time Binding means
– Compiler has enough information to determine an address
(offset)
– Named variables have their addresses hard-coded during
compilation
• Global variables are given offset from start of global
data area
• Local variables are given offset from top of stack
• Objects are given offset from start of object data
– executable code contains address references
©Copyright 2004, Cognizant Academy, All Rights Reserved 133
Operator overloading
• To overload means give it an additional meaning.
• Function definition syntax for operator overloading
©Copyright 2004, Cognizant Academy, All Rights Reserved 134
Operator overloading
• A way of achieving static polymorphism is Operator
overloading is just “syntactic sugar,” which means it
is simply another way for you to make a function call
• Example: the + (plus) operator in C++ behaves
differently depending on the operands:
4+5 - integer addition
3.14 + 2.0 - floating point addition
“sita” + "ram" - string concatenation
• In C++, this is called operator overloading
©Copyright 2004, Cognizant Academy, All Rights Reserved 135
Operator Overloading
• Syntax of Operator overloading FRIEND function
• Number of arguments in a friend function for
• Unary operator – 1
• Binary operator – 2
Keyword Operator to be overloaded
ReturnType operator OperatorSymbol (argument list)
{
\\ Function body
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 136
Operator Overloading
• Syntax of Operator overloading Class Member
• Number of arguments in a member function for
• Unary operator – 0
• Binary operator – 1
Operator to be overloaded
ReturnType classname :: OperatorSymbol (argument list)
{
\\ Function body
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 137
Operator Overloading
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
• Operators that can not be overloaded
∙ ٫ → ?: sizeof
©Copyright 2004, Cognizant Academy, All Rights Reserved 138
Unary Operators Overloading
• To declare a unary operator function as a nonstatic
member
»return-type operatorop()
• To declare a unary operator function as a global
function
»ret-type operatorop( arg )
©Copyright 2004, Cognizant Academy, All Rights Reserved 139
Unary Operators Overloading
class Point
{
public:
// Declare prefix and postfix increment operators.
Point& operator++(); // Prefix increment operator.
This function can be used as lvalue.
Point operator++(int); // Postfix increment operator.
// Declare prefix and postfix decrement operators.
Point& operator--(); // Prefix decrement operator.
Point operator--(int); // Postfix decrement operator.
// Define default constructor.
Point() {x = y = 0; }
// Define accessor functions.
int x1() { return x; }
int y1() { return y; }
private:
int x, y;
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 140
Unary Operators Overloading
// Define prefix increment operator.
Point& Point::operator++()
{ x++; y++; return *this;
}
// Define postfix increment operator.
Point Point::operator++(int)
{
Point temp = *this;
++*this;
return temp;
}
// Define prefix decrement operator.
Point& Point::operator--()
{ x--; y--; return *this;
}
// Define postfix decrement operator.
Point Point::operator--(int)
{ Point temp = *this; --*this; return temp;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 141
Unary Operators Overloading
• The same operators can be defined in file scope
(globally) using the following function heads:
friend Point& operator++( Point& ) // Prefix increment
friend Point& operator++( Point&, int ) // Postfix increment
friend Point& operator--( Point& ) // Prefix decrement
friend Point& operator--( Point&, int ) // Postfix decrement
©Copyright 2004, Cognizant Academy, All Rights Reserved 142
Binary Operator Overloading
• To declare a binary operator function as a nonstatic
member, you must declare it in the form:
»ret-type operatorop( arg )
• To declare a binary operator function as a global
function, you must declare it in the form:
»ret-type operatorop( arg1, arg2 )
©Copyright 2004, Cognizant Academy, All Rights Reserved 143
Binary Operator Overloading
Point Point::operator+ (Point P)
class Point { {
public: Point temp;
temp.x = x + P.x;
int x,y; temp.y = y + P.y;
Point () {}; return (temp);
Point (int,int); }
Point operator + (Point); int main ()
}; {
Point::Point (int a, int b) { Point a (3,1);
Point b (1,2);
x = a; Point c;
y = b; c = a + b; // c=a.operator+(b);
} cout << c.x << "," << c.y;
return 0;
2,3 }
©Copyright 2004, Cognizant Academy, All Rights Reserved 144
Assignment operator overloading
• Assignment operator (=) is, strictly speaking, a binary
operator. Its declaration is identical to any other binary
operator,
Exceptions:
• It must be a non-static member function. No operator = can
be declared as a non-member function.
• It is not inherited by derived classes.
• A default operator= function can be generated by the
compiler for class types if none exists (bitwise shallow copy)
• User defined operator= function performs member wise deep
copy.
©Copyright 2004, Cognizant Academy, All Rights Reserved 145
Assignment operator overloading
class Point
{
public:
Point &operator=( Point & ); // Right side is the argument.
...
};
// Define assignment operator.
Point &Point::operator=( Point &pt)
{
x = pt. x;
y = pt. y;
return *this;
// Assignment operator returns left side.}
©Copyright 2004, Cognizant Academy, All Rights Reserved 146
Overloading member function
class assign()
{
int a;
public:
operator + (assign var1);
};
assign :: operator+ (assign var1)
{ a = 2 + var1.a; }
assign object1,object2;
main( )
{
object1.a=5;
object2.a = object2+ object1;
cout<<“Object2.a is”<< object2.a<<“\n”; Object2.a is 7
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 147
Overloading member function
class complex()
{
double r,i;
public:
complex(double re,double im):r(re),i(im) { }
complex & operator + (complex & R);
};
complex complex::operator+ (complex &R)
{ return (r+ R.r,i+R.i); }
main( )
{
Complex d(1.0,1.0);
Complex b(1.0,1.0);
Complex c(0.0,0.0);
c=d.operator +(b); //c=b+d
return 0;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 148
Non-member operators
• If you want the left-hand operand to be an object of
some user defined class or predefined data types
(This is when the operators << and >> are
overloaded for iostreams) you should use a non
member function
©Copyright 2004, Cognizant Academy, All Rights Reserved 149
Non-member operators
friend Point operator+(int a, Point P)
// for the expression P1 = 7 + P2 in main prg
{
Point P1;
P1.x = a + P.x;
P1.y = a + P.y;
return P1;
}
ostream& operator<<(ostream& os, const Point&
a)
{ os << a.x;
os << a.y;
return os;
}
istream& operator>>(istream& is, Point& a)
{ is >> a.x;
is >> a.y;
return is;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 150
Type Conversion
• Objects of a given class type can be converted to objects of
another type
• This is done by constructing an object of the target class type
from the source class type and copying the result to the target
object. This process is called conversion by constructor
• Objects can also be converted by user-supplied conversion
functions Conversion Conversion takes Conversion
required palce in takes palce in
Source class Destination
class
Basic class Not applicable Constructor
Class basic Casting Operator Not Applicable
Class class Casting operator Constructor
©Copyright 2004, Cognizant Academy, All Rights Reserved 151
Type Conversion
// spec1_conversion_functions2.cpp int main()
// C2666 expected {
#include <string.h> String s( "abcd" );
class String char *ch = "efgh";
{ // Cause the compiler to
public: //select a conversion.
// Define constructor that converts return s == ch;
//from type char * }
String( char *s )
{ strcpy( _text, s ); } The compiler has two choices and no
// Define operator conversion function way of determining which is correct.
//to type char * (i)It can convert ch to an object of type
operator char *() String using the constructor and then
{ return _text; } perform the comparison using the
int operator==( const String &s ) user-defined operator==.
{ return !strcmp( _text, s._text (ii)It can convert s to a pointer of type
); } char * using the conversion function
private: and then perform a comparison of the
char _text[80]; pointers.
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 152
Operator Overloading
Restriction on using overloaded operators
• You cannot define new operators, such as **.
• You cannot redefine the meaning of operators when
applied to built-in data types.
• Overloaded operators must either be a non-static
class member function or a global function.
• Operators obey the precedence, grouping, and
number of operands dictated by their typical use
with built-in types.
• If an operator can be used as either a unary or a binary
operator (&, *, +, and -), you can overload each use
separately.
©Copyright 2004, Cognizant Academy, All Rights Reserved 153
Operator Overloading
• Unary operators declared as member functions take no
arguments; if declared as global functions, they take one
argument.
• Binary operators declared as member functions take one
argument; if declared as global functions, they take two
arguments.
• Overloaded operators cannot have default arguments.
• All overloaded operators except assignment (operator=) are
inherited by derived classes.
• The first argument for member-function overloaded
operators is always of the class type of the object for which
the operator is invoked No conversions are supplied for the
first argument.
©Copyright 2004, Cognizant Academy, All Rights Reserved 154
Polymorphism : Non–Virtual Functions
class B{
public: No matters style of call, function
void f(); name and object type serve as
}; basics for function body
class D: public B{
selection.
public:
// f() not overridden
}; All three calls of f( ) on derived
void main(){ class object d through the
Dd object, through a base class
B*bp=&d; pointer and through a derived
D*pd=&d;
d.f(); // B::f()
class pointer provides the same
pb->f(); //B::f() result.
pd->f(); // B::f()
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 155
Polymorphism : Virtual functions
Virtual Functions
• A member function that is declared as virtual in a base class
and redefined by a derived class.
• A virtual function defines a general class of actions . The
redefined virtual function implements a specific method.
• For non-virtual functions with the same name, the system
determines at compile time which of the function to invoke.
• For virtual methods with the same name the system
determines at run time which of the methods to invoke.
©Copyright 2004, Cognizant Academy, All Rights Reserved 156
Virtual Functions : Example 1
• A virtual function is a member function that you expect to be redefined in
derived class.
• A class member function can be made virtual by declaring it with the
virtual keyword in the base class.
class One
{
public:
void whoami()
{
cout<<”One”<<endl;
}
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 157
Virtual Functions : Example 1 contd…
class Two : public One
{
public:
void whoami()
{
cout<<”Two”<<endl;
}
};
class Three : public Two
{
public:
void whoami()
{
cout<<”Three”<<endl;
}
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 158
Virtual Functions : Example 1 contd…
int main()
{
One one ;
Two two; The Output is
Three three;
One * array[3]; One
One
array[0]=&one;
One
array[1]=&two;
array[2]=&three;
for(int i=0;i<3;i++)
array[i]->whoami();
return EXIT_SUCCESS;
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 159
Virtual Functions : Binding
• In static binding the data type of the pointer resolves
which method is invoked.
• It would be nice if the output were One, Two, Three.
• If whoami is made virtual, the system determines at
runtime which of the three whoami to invoke.
• In dynamic binding , The type of the object pointed
to resolve which method is invoked.
©Copyright 2004, Cognizant Academy, All Rights Reserved 160
Virtual Functions : Example 2
Class B
{ int main()
int x; {
public: D d;
virtual void g();
B *ptr = &d;
int h();
ptr->h(); B::h invoked
};
class D : public B ptr->g(); D::h invoked
{ }
int y;
public:
void g();
int h();
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 161
Virtual Functions : Example 3
class Base { int main()
public: {
virtual void fun(){
cout<<”This is base fun().\n”; Base *ptr B;
} Derived0 D0;
}; Derived1 D1;
class Derived0 : public Base{ ptr=&B;
public: ptr->fun();
void fun(){
cout<<” This is derived0 fun(). \n”;} ptr=&D0;
}; ptr->fun();
class Derived1 : public Base{ ptr=&D1;
public: p->fun();
void fun(){ return 0;
cout<<” This is derived1 fun() . \n”;
} }
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 162
Virtual Functions : Example 3 contd..
Output
This is base fun()
This is derive0 fun()
This is derive1 fun()
©Copyright 2004, Cognizant Academy, All Rights Reserved 163
Virtual Functions : Constructors
• Virtual functions should be member functions.
• To construct an object , a constructor needs the
exact type of the object it is to create.
• So a constructor can not be virtual but a destructor
can be.
©Copyright 2004, Cognizant Academy, All Rights Reserved 164
Virtual Functions : Constructors contd…
class B { main()
public: {
B( ) { this->f(); } D d;
virtual void f() cout<<”object d was created
{ successfully”<<endl;
cout<<”Executing B::f()”<<endln; d.f();
}
}
};
class D: public B {
public: output
D( ){ } Executing B::f()
virtual void f( ) object d created
{ successfully.
cout<<”Executing D::f()”<<endl; Executing D::f()
}
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 165
Virtual Functions : Destructors
class B {
char * ptrB;
public:
B() {
ptrB=new char[5];
cout<<”B allocates 5 bytes”<<endl;
}
~B() {
delete []ptrB;
cout<<”B frees 5 bytes”<<endl;
}
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 166
Virtual Functions : Destructors contd…
class D: public B {
char*ptrD;
public:
D( ) : B() {
ptrD=new char[1000];
cout<<”D allocates 1000 bytes”<<endl;
}
~D() {
delete[] ptrD;
cout<< “ D frees 1000 bytes “ << endl;
}
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 167
Virtual Functions : Destructors contd…
int main(){ The Memory will be exhausted, in each
const int forever =1; call of function f( ),
void f();
while(forever) B allocates 5 bytes
D allocates 1000 bytes
f();
B frees 5 bytes.
return EXIT_SUCCESS;
}
void f(){ As p is of type B*, p is bound to B’s
B*p=new D; data members and methods, including
constructors and destructors rather than
delete p; to D’s methods .
} When f exits B::~B frees the 5 bytes.
D::~D() fails to fire.
©Copyright 2004, Cognizant Academy, All Rights Reserved 168
Virtual Function : Default Arguments
class Base {
public:
virtual int foo(int ival=1024){
cout<<”base::foo()—ival :”<<ival <<endl;
return ival;
}
};
class Derived :: public Base{
public:
virtual int foo(int ival=2048){
cout<<”derived::foo() – ival :”
<< ival << endl;
return ival;
}
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 169
Virtual Function : Default Arguments contd…
int main () {
Derived *pd=new derived; The default argument to be passed
Base *pb=pd; to foo() is not determined at run
int val = pb->foo(); time, rather it is determined at
cout<<”main : val through base “ compile time and is based on the
<<val<<endl; type of the object through which the
val = pd->foo(); function is being invoked.
cout<<”main : val through derived
“<<val<<endl;
}
Output
derived:: foo() – ival : 1024
main : val through base : 1024
Derived :: foo() – ival : 2048
main : val through derived : 2048
©Copyright 2004, Cognizant Academy, All Rights Reserved 170
Abstract Class & Pure Virtual Functions
Abstract Class
– A class that serves only as a base class from which other classes
can be derived ;
– no instance of an abstract base class are ever created.
– If a base class declares a pure virtual functions , no instance of the
class can be created, and so it is necessarily an abstract base class.
Pure Virtual Functions
– A virtual function that is declared in a base but not defined there ;
– responsibility for defining the function falls on the derived classes,
each of which generally provides a different definition.
©Copyright 2004, Cognizant Academy, All Rights Reserved 171
Pure Virtual Function
class Base {
class Derv2 : public Base{
public: public:
virtual void show()=0 void show(){cout<<”\n In Derv2”;
// Pure Virtual function }
}; };
class Derv1 : public Base {
void main(){
public: Base *List[2];
void show(){ Derv1 dv1;
cout<<”\n Derv 1”; } Derv2 dv2;
}; List[0]=&dv1;
List[1]=&dv2;
List[0]->show();
List[1]->show();
}
©Copyright 2004, Cognizant Academy, All Rights Reserved 172
Virtual Function & Private/Protected Derivation
Polymorphism does not work with private or
protected derivation
class Base{
public: Standard conversions don’t
virtual void f(); convert derived class pointers to
}; base class pointers with
class Derived : private Base{ private/protected derivation.
public:
void f(); Always use public inheritance
}; with polymorphism.
Base *ptr, b;
Derived d;
ptr=&d; // illegal
ptr=&b; // ok
ptr->f(); // calls B::f()
©Copyright 2004, Cognizant Academy, All Rights Reserved 173
Virtual Function Implementation
• Most compiler build a virtual function table for each
polymorphic class. All object of the same class share the
same virtual function table(vtable).
• The vtable is an array of pointers to virtual functions that
have definitions in either a base class or a derived class .
• The value of the pointer depends on whether or not the
derives class override a base class virtual function with a
new version of its own.
• A polymorphic class with at least one virtual function
includes a hidden pointer (vptr) to its object which points to
vtable.
©Copyright 2004, Cognizant Academy, All Rights Reserved 174
Virtual Function Implementation contd…
Base b1; Base vtbl;
Base::f1()
Base Members Base::f2()
Base::f3()
vptr
Derived vtbl;
Derived d1;
Base::f1()
Base Members Derived::f2()
Base::f3()
vptr
Derived::f4()
Derived Members
©Copyright 2004, Cognizant Academy, All Rights Reserved 175
Virtual Function – Example 4
class Base{ Base b1;
public : Derived d1;
Base() { } Base *p=&d1;
virtual void f1() { cout<<”base::f1( )” << endl; } p->f4(); // illegal
virtual void f2( ) { cout << Base:: f2()”<<endl; } Derived *q=&d1;
virtual void f3() { cout<<”Base :: f3()”<<endl; } q->f4() ;// legal
};
class Derived {
public: With the help of base
Derived() { } class pointer, we can’t
access any derived
void f2() { cout<<”Derived ::f2()”<<endl; }
class members.
virtual void f4() { cout<<Derived ::f4()”<,endl;}
};
©Copyright 2004, Cognizant Academy, All Rights Reserved 176
Object Oriented Programming: Next
Step
ll Description Reference Topic or
Module
Book OO A & D by Grady Booch All
Book Object oriented software concepts by All
Bertrand Mayer
PDF http://www.kbcafe.com/articles/OOP.Concepts.pdf
All
URL http://www.desy.de/gna/html/cc/Tutorial/tutorial.html
All
http://www.bitpipe.com/rlist/term/Object-Oriented-Programming.html
All
http://www.well.com/user/ritchie/oo.html All
http://www.planetpdf.com/codecuts/pdfs/ooc.pdf
All
©Copyright 2004, Cognizant Academy, All Rights Reserved 177
Congratulations!
You have successfully
completed
Object Oriented
Programming