SlideShare a Scribd company logo
1 of 178
Object Oriented
Programming
Knowledge Level:
Basic
2
©Copyright 2004, Cognizant Academy, All Rights Reserved
About the Author
Created By: Cognizant Academy
Version and
Date:
OOPSCONCPT/PPT/0404/1.0
3
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
4
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
Programming
paradigms
2
OOPS
Concepts
3
Functions in
C++
5
Inheritance
6
Polymorphism
4
Classes and
Objects
5
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
6
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
Programming Paradigms : Overview
7
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
8
©Copyright 2004, Cognizant Academy, All Rights Reserved
Procedural Programming
Sub-programs
Global data
• 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)
9
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
10
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
Modules
Global data
Local Data Local Data Local Data Sub-programs
11
©Copyright 2004, Cognizant Academy, All Rights Reserved
• Three types of control flow are used:
- sequence
- selection
- iteration
Structured Programming
Y/N
12
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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
Structured Programming
13
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
14
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
15
©Copyright 2004, Cognizant Academy, All Rights Reserved
 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 Oriented Programming
Data variable
Member Function
Data variable
Member Function
Data variable
Member Function
Object A
Object B
Object C
16
©Copyright 2004, Cognizant Academy, All Rights Reserved
Object Oriented Programming
• Does not deal with programming in the sense of
developing algorithms or data-structures
• Focuses on ADT
17
©Copyright 2004, Cognizant Academy, All Rights Reserved
POA Vs OOA
Director Cell
H/W Components
Room
Service Engineer
Room
System assembled with the
supplied H/w components
Send H/w +
Instructions to
assemble the
system
Fetch Components
Procedure Oriented Approach:
18
©Copyright 2004, Cognizant Academy, All Rights Reserved
Object Oriented Approach:
19
©Copyright 2004, Cognizant Academy, All Rights Reserved
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)
20
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
21
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
22
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
23
©Copyright 2004, Cognizant Academy, All Rights Reserved
Class & Object
Account
acct_no
name
balance
withdraw()
deposit( )
431245
Patrick
50567.78
431246
Meyer
35567.78
Account:acct1 Account:acct2
24
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
25
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
26
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
27
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
28
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
Data Abstraction
29
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
Data Abstraction
30
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
31
©Copyright 2004, Cognizant Academy, All Rights Reserved
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 )
32
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
33
©Copyright 2004, Cognizant Academy, All Rights Reserved
Inheritance
Account
acct_no
name
balance
withdraw()
deposit( )
Savings Acc
interest
Current Acc
overdraft
34
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
35
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
36
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
};
37
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
38
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
39
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
}
40
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
}
41
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
42
©Copyright 2004, Cognizant Academy, All Rights Reserved
Functions in C++
• References
• Function Overloading
• Default values
• Inline Functions
• Function Templates
• Friend Functions
• Static Members and Functions
• Constant Functions and Constant data members
43
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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;
}
Parameter passing mechanisms
44
©Copyright 2004, Cognizant Academy, All Rights Reserved
• Call by value: another example
main( )
{
int x,y; //actual args
void change(int,int);
x=4; y=5;
change(x, y);
}
void change(int a, int b)
{ //a,b formal args
int k;
k=a; a=b; b=k;
}
4
x
5
y
5
a
4
b
Parameter passing mechanisms
45
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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;
}
Parameter passing mechanisms
46
©Copyright 2004, Cognizant Academy, All Rights Reserved
• Call by address: another example
main( )
{
int x,y; //actual args
void change(int *,int*);
x=4; y=5;
change(&x, &y);
}
void change(int *a, int *b)
{ //a,b formal args
int *k;
*k=*a; *a=*b; *b=*k;
}
4
x
5
y
Parameter passing mechanisms
47
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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;
}
Parameter passing mechanisms
48
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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.
References
Const pointer – Initialized to actualint
cannot point to another variable
int actualint = 123;
int *const intptr = &actualint;
49
©Copyright 2004, Cognizant Academy, All Rights Reserved
• Value of a reference cannot be changed
int actualint = 123;
int &otherint = actualint;
123
actualint otherint
otherint++
124
otherint++
References & Constants
int & const otherint = actualint; // Error
Meaningless as all references are constants
by definition
50
©Copyright 2004, Cognizant Academy, All Rights Reserved
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:
DataType & ReferenceVariable = ValueVariable
Standard or user defined data type: char, short, int, float, etc.
Reference operator
C++ alias variable
C++ value variable
51
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
ref
1
count
ref
2
52
©Copyright 2004, Cognizant Academy, All Rights Reserved
• Reference to a constant:
Possible
• Constant reference
declaration:
Not Possible
int actualint = 123;
const int &otherint = actualint;
•readonly alias for actualint
•can’t make any modification
int & const otherint = actualint;
// Error
• Meaningless as all references
are constants by definition
References and pointers
53
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
54
©Copyright 2004, Cognizant Academy, All Rights Reserved
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)
55
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.;
}
Function Overloading
56
©Copyright 2004, Cognizant Academy, All Rights Reserved
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);
Function Overloading
57
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
58
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
59
©Copyright 2004, Cognizant Academy, All Rights Reserved
• Examples:
// Declarations //Function calls
int add(int a, int b); // prototype 1
int add(int a, int b, int c); // prototype 2
double add(double x, double y) // prototype 3
double add(int p, double q) // prototype 5
double add(double p,int q) // prototype 5
cout<<add(15,10);
cout<<add(15,10.5);
cout<<add(15.5,10.5);
cout<<add(15,10,5);
cout<<add(0.15,1.05);
Default Values
60
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
61
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
62
©Copyright 2004, Cognizant Academy, All Rights Reserved
Inline Functions
inline ReturnType FunctionName(Parameters)
{
// Body of a main function
}
Keyword, function qualifier
Syntax of inline function definition:
63
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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.
inline int sqr(int num)
{ return num * num; }
void main( )
{ ---
a=sqr(5);
b=sqr(n);
---
}
void main( )
{ ---
a = 5 * 5;
b = n * n;
---
}
preprocessor
Inline Functions
64
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
65
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
Inline Functions versus Macros
66
©Copyright 2004, Cognizant Academy, All Rights Reserved
# define SQUARE(num) num * num
inline float square(float j)
{
return (j * j);
}
void main( )
{ int p=3,q=3,r,s;
r=SQUARE(++p);
s=square(++q);
cout<<“r = “ << r << “s = “<<s;
}
Output r =25 s =16
Macro SQUARE( ) expands into
r = ++num * ++num
 In macro expansion
num is incremented twice.
Inline function square( )
 var ‘q’ is incremented only
once and is assigned to j
then j * j.
Inline Functions versus Macros
67
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
68
©Copyright 2004, Cognizant Academy, All Rights Reserved
Static Members contd.,
• Static Data Members:
Object A
Object B
Object C
Static variable
69
©Copyright 2004, Cognizant Academy, All Rights Reserved
• Static Member Example
class account {
private:
int currentBal;
static int RateofInt;
};
myclass A(0), B(1);
currentBal=0
Object A
Object
B
Shared by
all objects
Static Members contd.,
currentBal=1
70
©Copyright 2004, Cognizant Academy, All Rights Reserved
Static Members contd.,
• Static Data Members:
class SavingsAccount
{
private:
char name[30];
float total;
float CurrentRate;
public:
SavingsAccount();
void EarnInterest()
{
total + = CurrentRate * total;
}
}
Only one copy should
be available as all
objects should have
same Interest rate
Declare CurrentRate as
static float CurrentRate;
To make CurrentRate
accessible to all objects
71
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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
Constant data member and Constant Functions
72
©Copyright 2004, Cognizant Academy, All Rights Reserved
• The const keyword specifies that a variable's value is
constant and tells the compiler to prevent the programmer
from modifying it.
• 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.
int main()
{
const int i = 5;
---
}
Constant data member and Constant Functions
73
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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( );
---
}
Constant data member and Constant Functions
74
©Copyright 2004, Cognizant Academy, All Rights Reserved
class Time
{
int hour;
public:
Time(int k) { hour=k; }
void update( ) { hour++; }
int value( ) const { return hour; }
void cheat( ) const { hour++; }
};
void main (void)
{
Time t(10);
cout<<t.value( );
}
// error this is const
11
Constant data member and Constant Functions
75
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
76
©Copyright 2004, Cognizant Academy, All Rights Reserved
template < class identifier >
ReturnType FunctionName(arguments of type identifier)
Function Templates
template < class T > // or template< typename T >
T square( T value1 )
{
return value1 * value1;
}
Keyword for declaring function template
Keyword class
Name of the template data-type
Function parameters of type
template, primitive or user-defined
77
©Copyright 2004, Cognizant Academy, All Rights Reserved
Examples:
Convert function to convert a float Fahrenheit temperature to
Celsius
Function Templates
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.;
}
78
©Copyright 2004, Cognizant Academy, All Rights Reserved
Function Templates
// definition of function template maximum
template < class T >
// or template < typename T >
T maximum( T value1, T value2, T value3 )
{
T max = value1;
if ( value2 > max )
max = value2;
if ( value3 > max )
max = value3;
return max;
}
maximum( int1, int2, int3 )
maximum( double1, double2, double3 )
maximum( char1, char2, char3 )
In main( )
1, 2, 3
1.1 , 2.1, 1.8
A, B,C
Input values
3
2.1
C
Output
Maximum value
79
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
80
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
81
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
82
©Copyright 2004, Cognizant Academy, All Rights Reserved
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).
83
©Copyright 2004, Cognizant Academy, All Rights Reserved
Constructors contd.,
class sum
{
public:
int x, y;
sum( );
};
sum::sum(void)
{
cout<<" Inside sum( )n";
x=2;y=4; // if not initialized garbage
}
void main( )
{
sum s;
cout<<"Inside main( )n";
cout<<"x= " << s.x<<"y= "<<s.y;
}
Inside sum( )
Inside main( )
x= 2 y= 4
Constructor declared
Object created and
initialized by
constructor
Constructor defined
Object s x= 2
y= 4
84
©Copyright 2004, Cognizant Academy, All Rights Reserved
Constructors with arguments
• Parameters can be passed to the constructors
class sum
{
public:
int x, y;
sum(int i,int j);
};
sum::sum(int i,int j)
{
x=i;y=j;
}
void main( )
{
sum s1(10,20);
sum s2 = sum(30,40);
cout<<"x= " << s1.x<<"y= "<<s1.y;
cout<<"x= " << s2.x<<"y= "<<s2.y;
}
x= 10 y= 20
Parameterized Constructor
Object s1
Object s2 x= 30 y= 40
Constructor called implicitly
85
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;};
sum(int, int) {x=i;y=j;};
sum(sum & i) {x=i.x;y=i.y;};
Two arguments
Copy constructor
No arguments
86
©Copyright 2004, Cognizant Academy, All Rights Reserved
Constructors with default arguments
• Constructors can be defined with default arguments
class sum
{
public: int x, y;
sum(int i, int j=10);
};
sum::sum(int i,int j)
{x=i;y=j;}
void main()
{
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;
}
x= 1 y= 10
Object s1
Object s2 x= 8 y= 9
Default value for
j=10 (Used by the
object s1)
87
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
88
©Copyright 2004, Cognizant Academy, All Rights Reserved
Copy Constructors contd.,
class sum
{
public:
int x;
sum(){ }
sum(int i) {x=i;}
sum(sum &j) {x=j.x;}
};
void main()
{
sum s1(10);
sum s2(s1);
sum s3=s1;
sum s4;
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
x=10 x=10
x=10 x=10
s1 s2 s3 s4
89
©Copyright 2004, Cognizant Academy, All Rights Reserved
#include<string.h>
class String
{
char* data;
public:
String(const char* s = "")
{
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()
{
cout << data;
}
};
int main()
{
String s = "hello"; // same as String s("hello");
cout <<”s=”<<s.display( );
String empty;
cout<<”empty=”<<empty.display();
}
s = hello
empty=
Copy Constructors contd.,
90
©Copyright 2004, Cognizant Academy, All Rights Reserved
int main()
{
String s = "hello";
String t = s; // same as String t(s);
s.display( );
t.display( );
t.assign(“world”);
s.display( );
t.display( );
}
hello
hello
world
world
hello0
data
data
Copy Constructors contd.,
Shallow Copy
91
©Copyright 2004, Cognizant Academy, All Rights Reserved
String(const String& s)
{
data = new char[strlen(s.data)+1];
strcpy(data, s.data);
} Deep Copy
Deep copy
hello0
data
data
hello0
Copy Constructors contd.,
92
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
93
©Copyright 2004, Cognizant Academy, All Rights Reserved
Destructors contd.,
Declaration
– Same name as class
• Preceded with tilde (~)
~sum( ) { }
94
©Copyright 2004, Cognizant Academy, All Rights Reserved
Constant Objects
const objects using const keyword before object
declaration.
For example:
const sample s ( m, n); // object s is constant
95
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
96
©Copyright 2004, Cognizant Academy, All Rights Reserved
Static Object Example
#include<iostream.h>
class account
{ int acc_no;
public:
account()
{cout<<"Account constructor"; }
~account()
{cout<<"Account desctructor"; }
};
void create_stobj()
{ account vip;
}
void main(void)
{
clrscr();
account acc1;
create_stobj();
getch();
}
Account constructor
Account constructor
Account destructor
Account constructor
Account constructor
97
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
98
©Copyright 2004, Cognizant Academy, All Rights Reserved
#include <iostream.h>
class two
{
int a,b;
public:
void let(int x, int y)
{ a=x; b=y; }
void print(void)
{cout<<"a="<<a<<" b="<<b; }
void assign(one x)
{
a=x.a1;
b=x.b1;
}
};
class one
int a1,b1;
public:
one(void)
{ a1=5, b1=10;
}
friend class two;
};
void main(void)
{ one o1;
two t1;
t1.let(4,2);
t1.print();
t1.assign(o1);
t1.print();
}
a = 4 b= 2
a= 5 b=10
Friend class example
99
©Copyright 2004, Cognizant Academy, All Rights Reserved
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( );
y.sum(2.2, 3.7);
y.print( ); }
The sum is : 5
The sum is : 5.9
100
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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.
4. Inheritance
101
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
102
©Copyright 2004, Cognizant Academy, All Rights Reserved
Inheritance
Student
Reg.No.
Course
Marks
Teaching Staff
Edn.Qual.
Designation
Specialization
Person
Name
Sex
Age
“Person” is a generalization of “Student”.
“Student” is a specialization of “Person”.
103
©Copyright 2004, Cognizant Academy, All Rights Reserved
Defining Derived Class
• The general form of deriving a subclass from a base class is
as follows
• 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.
Class derived-class-name : visibility-mode base-class-name
{
……………… //
……………….// members of the derived class
};
104
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
105
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
Person
Student subclass(derived class)
superclass(base class)
class Person
{ ….. };
class Student : public Person
{
…………
};
visibility mode
106
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
Student
CS -Student
Class Person
{ ……};
Class Student : public Person
{ ……};
Class CS -Student : public Student
{ …….};
107
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
Part-time Student
Class Employee
{……..};
Class Student
{……..};
Class Part-time Student : public Employee,
public Student
{…….};
108
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
Person
Student Employee
Class Person
{……};
Class Student : public Person
{……};
Class Employee : public Person
{……};
109
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
Student
PG - Student
Gate Score
Class Person
{ ……};
Class Student : public Person
{ ……};
Class Gate Score
{…….};
Class PG - Student : public Student
public Gate Score
{………};
110
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
111
©Copyright 2004, Cognizant Academy, All Rights Reserved
Person
Student Employee
Part-time Student
Virtual Inheritance
Class Person
{……};
Class Student : public Person
{……};
Class Employee : public Person
{……};
Class Part-time Student : public Student,
public Employee
{…….};
112
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
113
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
114
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
115
©Copyright 2004, Cognizant Academy, All Rights Reserved
Access Specifiers with Inheritance
Class X
{
int priv;
protected:
int prot;
public:
int publ;
void m( );
};
void X::m( )
{
priv =1; //Ok
prot =1; //Ok
publ =1; //Ok
}
class Y : public X
{ void mderived( ); }
Y::mderived( )
{
priv =1; //Error priv is private and
//cannot be inherited
prot =2; // Ok
publ=3; // Ok
}
void global_fun(Y *p)
{
p->priv = 1; //Error : priv is
//private of X
p->prot = 2; //Error : prot is
//protected and the function global_fun( )
// is not a friend or a member of X or Y
p->publ =3; // Ok
}
116
©Copyright 2004, Cognizant Academy, All Rights Reserved
Public, Protected and Private derivation
private :
int a1;
protected :
int a2;
public :
int a3;
private :
int b1;
protected :
int b2;
public :
int b3;
private :
int b1;
protected:
int a2;
int b2
public:
int b3;int a3;
Public Derivation
Class A Class B Class B: Public A
117
©Copyright 2004, Cognizant Academy, All Rights Reserved
Public derivation - example
class A
{
private : int a;
protected: int b;
public : void get_a( ) { cin>>a;}
void get_b( ) { cin>>b;}
void print_a( ) { cout<<a;}
void print_b( ) {cout<<b;}
};
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; }
};
void main( )
{
B b1;
b1.get_a( );
b1.get_b( );
b1.get_c( );
b1.get_d( );
b1.print_all( );
}
118
©Copyright 2004, Cognizant Academy, All Rights Reserved
Protected derivation - example
private :
int a1;
protected :
int a2;
public :
int a3;
private :
int b1;
protected :
int b2;
public :
int b3;
private :
int b1;
protected:
int a2;
int b2,a3;
public:
int b3;
Protected Derivation
• 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
119
©Copyright 2004, Cognizant Academy, All Rights Reserved
Protected derivation - example
class A
{
private: int a;
protected: int b;
public : void get_a( ) { cin>>a;}
void get_b( ) { cin>>b;}
void print_a( ) { cout<<a;}
void print_b( ) {cout<<b;}
};
class B : protected A
{ 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;};
}
void main( )
{
B b1;
b1.get_a( ); //ERROR
b1.get_b( ); //ERROR
b1.get_ab( );
b1.get_c( );
b1.get_d( );
b1.print_all( );
}
120
©Copyright 2004, Cognizant Academy, All Rights Reserved
Private derivation - example
The inherited public and protected members of a private
derivation become private members of the derived class.
private :
int a1;
protected :
int a2;
public :
int a3;
private :
int b1;
protected :
int b2;
public :
int b3;
private :
int b1;
int a2,a3;
protected:
int b2;
public:
int b3;
Private Derivation
Class A Class B Class B : private A
121
©Copyright 2004, Cognizant Academy, All Rights Reserved
Private derivation - example
class A
{
private: int a;
protected: int b;
public : void get_a( ) { cin>>a;}
void get_b( ) { cin>>b;}
void print_a( ) { cout<<a;}
void print_b( ) {cout<<b;}
};
class B : private A
{
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_abcd( ) { print_a( ); cout<<b<<c<<d;
}
};
Class C : public B
{ public :
void get_all( )
{ get_a( ); //ERROR
get_b( ); //ERROR
get_ab( ); //Ok
get_c( ); //Ok
get_d( ); //Ok }
void print_all( )
{ print_a( ); //ERROR
print_b( ); //ERROR
print_cd( ); //Ok
print_abcd( ); //Ok } };
void main( )
{ C c1;
c1.get_a( ); //ERROR
c1.get_b( ); //ERROR
c1.get_c( ); // Ok
c1.get_d( ); //Ok
c1.getall( ); //Ok
c1.print_all( ); //Ok }
122
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
123
©Copyright 2004, Cognizant Academy, All Rights Reserved
Derived Class Constructors
class B
{
int x;
public :
B( ) { cout<<”B::B( ) Fires…”<<endl;}
};
class D : public B
{
int y;
public :
D( ) { cout<<”D::D( ) Fires…”<<endl;}
};
void main( )
{
D d;
}
B::B( ) Fires…
D::D( ) Fires…
124
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
public :
D( ) { b =0; cout<<”D::D( ) Fires…”<<endl;}
D(int x) { b =x; cout<<”D::D(int) Fires…”<<endl;}
D(int x, int y) : B(y)
{ b =x; cout<<”D::D(int, int) Fires…”<<endl;}
};
void main( )
{
D d;
D d(10);
D d(10, 20);
}
B::B( ) Fires…
D::D( ) Fires…
B::B( ) Fires…
D::D(int) Fires…
B::B(int) Fires…
D::D(int, int) Fires…
125
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;}
};
class D : public B
{
int y;
public :
D( ) { cout<<”D Constructor Invoked …”<<endl;}
~ D( ) { cout<<”D Destructor Invoked…”<<endl;}
};
void main( )
{ D d; }
B Constructor Invoked…
D Constructor Invoked…
D Destructor Invoked…
B Destructor Invoked …
126
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
{
protected : int a;
public :
void getdata( ) { cin>>a;}
void putdata( ) { cout << a;}
};
class B : public A
{
protected: int b;
public : void getdata( )
{ cin>>a>>b;}
void putdata( ) { cout<<a<<b;}
};
void main( )
{
B b1;
b1.getdata( ); // B::getdata( )
//is invoked
b1.putdata( ); // B::putdata( )
//is invoked
b1.A::getdata( ); // A::getdata( )
// is invoked
b1.A::putdata( ); // A::putdata( )
//is invoked
}
127
©Copyright 2004, Cognizant Academy, All Rights Reserved
Composition
class x
{ int i;
public:
x()
{i=0;}
void set(int j)
{ i=j;}
int read() const
{ return i;}
};
class y
{
int i;
public:
X x;
Y()
{ i=0;}
void f(intj)
{ i=j;}
int g() const
{ return i;}
};
int main()
{ Y y;
y.f(5);
y.x.set(10);
}
• Classes having objects of other classes as their data
members - composite classes
128
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
129
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
130
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
131
©Copyright 2004, Cognizant Academy, All Rights Reserved
Types of polymorphism
Polymorphism
Operator
Overloading
Function
Overloading
Static
Polymorphism
Dynamic
Polymorphism
Virtual Fucntion
132
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
133
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
134
©Copyright 2004, Cognizant Academy, All Rights Reserved
• To overload means give it an additional meaning.
• Function definition syntax for operator overloading
Operator overloading
135
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
136
©Copyright 2004, Cognizant Academy, All Rights Reserved
Operator Overloading
• Syntax of Operator overloading FRIEND function
• Number of arguments in a friend function for
• Unary operator – 1
• Binary operator – 2
ReturnType operator OperatorSymbol (argument list)
{
 Function body
}
Keyword Operator to be overloaded
137
©Copyright 2004, Cognizant Academy, All Rights Reserved
Operator Overloading
• Syntax of Operator overloading Class Member
• Number of arguments in a member function for
• Unary operator – 0
• Binary operator – 1
ReturnType classname :: OperatorSymbol (argument list)
{
 Function body
}
Operator to be overloaded
138
©Copyright 2004, Cognizant Academy, All Rights Reserved
• Operators that can not be overloaded
Operator Overloading
∙ ٫ → ?: sizeof
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
139
©Copyright 2004, Cognizant Academy, All Rights Reserved
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 )
140
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
};
141
©Copyright 2004, Cognizant Academy, All Rights Reserved
// 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;
}
Unary Operators Overloading
142
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
• The same operators can be defined in file scope
(globally) using the following function heads:
Unary Operators Overloading
143
©Copyright 2004, Cognizant Academy, All Rights Reserved
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 )
144
©Copyright 2004, Cognizant Academy, All Rights Reserved
Binary Operator Overloading
class Point {
public:
int x,y;
Point () {};
Point (int,int);
Point operator + (Point);
};
Point::Point (int a, int b) {
x = a;
y = b;
}
Point Point::operator+ (Point P)
{
Point temp;
temp.x = x + P.x;
temp.y = y + P.y;
return (temp);
}
int main ()
{
Point a (3,1);
Point b (1,2);
Point c;
c = a + b; // c=a.operator+(b);
cout << c.x << "," << c.y;
return 0;
}
2,3
145
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
146
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.}
Assignment operator overloading
147
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
148
©Copyright 2004, Cognizant Academy, All Rights Reserved
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);
return 0;
}
//c=b+d
149
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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
Non-member operators
150
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
}
151
©Copyright 2004, Cognizant Academy, All Rights Reserved
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
required
Conversion takes
palce in
Source class
Conversion
takes palce in
Destination
class
Basic class Not applicable Constructor
Class basic Casting Operator Not Applicable
Class class Casting operator Constructor
152
©Copyright 2004, Cognizant Academy, All Rights Reserved
// spec1_conversion_functions2.cpp
// C2666 expected
#include <string.h>
class String
{
public:
// Define constructor that converts
//from type char *
String( char *s )
{ strcpy( _text, s ); }
// Define operator conversion function
//to type char *
operator char *()
{ return _text; }
int operator==( const String &s )
{ return !strcmp( _text, s._text );
}
private:
char _text[80];
};
int main()
{
String s( "abcd" );
char *ch = "efgh";
// Cause the compiler to
//select a conversion.
return s == ch;
}
Type Conversion
The compiler has two choices and no
way of determining which is correct.
(i)It can convert ch to an object of type
String using the constructor and then
perform the comparison using the
user-defined operator==.
(ii)It can convert s to a pointer of type
char * using the conversion function
and then perform a comparison of the
pointers.
153
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
Operator Overloading
154
©Copyright 2004, Cognizant Academy, All Rights Reserved
• 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.
Operator Overloading
155
©Copyright 2004, Cognizant Academy, All Rights Reserved
Polymorphism : Non–Virtual Functions
class B{
public:
void f();
};
class D: public B{
public:
// f() not overridden
};
void main(){
D d
B*bp=&d;
D*pd=&d;
d.f(); // B::f()
pb->f(); //B::f()
pd->f(); // B::f()
}
No matters style of call, function
name and object type serve as
basics for function body
selection.
All three calls of f( ) on derived
class object d through the
object, through a base class
pointer and through a derived
class pointer provides the same
result.
156
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
157
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
}
};
158
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
}
};
159
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Functions : Example 1 contd…
int main()
{
One one ;
Two two;
Three three;
One * array[3];
array[0]=&one;
array[1]=&two;
array[2]=&three;
for(int i=0;i<3;i++)
array[i]->whoami();
return EXIT_SUCCESS;
}
The Output is
One
One
One
160
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
161
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Functions : Example 2
Class B
{
int x;
public:
virtual void g();
int h();
};
class D : public B
{
int y;
public:
void g();
int h();
};
int main()
{
D d;
B *ptr = &d;
ptr->h(); B::h invoked
ptr->g(); D::h invoked
}
162
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Functions : Example 3
class Base {
public:
virtual void fun(){
cout<<”This is base fun().n”;
}
};
class Derived0 : public Base{
public:
void fun(){
cout<<” This is derived0 fun(). n”;}
};
class Derived1 : public Base{
public:
void fun(){
cout<<” This is derived1 fun() . n”;
}
};
int main()
{
Base *ptr B;
Derived0 D0;
Derived1 D1;
ptr=&B;
ptr->fun();
ptr=&D0;
ptr->fun();
ptr=&D1;
p->fun();
return 0;
}
163
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Functions : Example 3 contd..
Output
This is base fun()
This is derive0 fun()
This is derive1 fun()
164
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
165
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Functions : Constructors contd…
class B {
public:
B( ) { this->f(); }
virtual void f()
{
cout<<”Executing B::f()”<<endln;
}
};
class D: public B {
public:
D( ){ }
virtual void f( )
{
cout<<”Executing D::f()”<<endl;
}
};
main()
{
D d;
cout<<”object d was created
successfully”<<endl;
d.f();
}
output
Executing B::f()
object d created
successfully.
Executing D::f()
166
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
}
};
167
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
}
};
168
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Functions : Destructors contd…
int main(){
const int forever =1;
void f();
while(forever)
f();
return EXIT_SUCCESS;
}
void f(){
B*p=new D;
delete p;
}
The Memory will be exhausted, in each
call of function f( ),
B allocates 5 bytes
D allocates 1000 bytes
B frees 5 bytes.
As p is of type B*, p is bound to B’s
data members and methods, including
constructors and destructors rather than
to D’s methods .
When f exits B::~B frees the 5 bytes.
D::~D() fails to fire.
169
©Copyright 2004, Cognizant Academy, All Rights Reserved
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;
}
};
170
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Function : Default Arguments contd…
int main () {
Derived *pd=new derived;
Base *pb=pd;
int val = pb->foo();
cout<<”main : val through base “
<<val<<endl;
val = pd->foo();
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
The default argument to be passed
to foo() is not determined at run
time, rather it is determined at
compile time and is based on the
type of the object through which the
function is being invoked.
171
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
172
©Copyright 2004, Cognizant Academy, All Rights Reserved
Pure Virtual Function
class Base {
public:
virtual void show()=0
// Pure Virtual function
};
class Derv1 : public Base {
public:
void show(){
cout<<”n Derv 1”; }
};
class Derv2 : public Base{
public:
void show(){cout<<”n In Derv2”;
}
};
void main(){
Base *List[2];
Derv1 dv1;
Derv2 dv2;
List[0]=&dv1;
List[1]=&dv2;
List[0]->show();
List[1]->show();
}
173
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Function & Private/Protected Derivation
Polymorphism does not work with private or
protected derivation
class Base{
public:
virtual void f();
};
class Derived : private Base{
public:
void f();
};
Base *ptr, b;
Derived d;
ptr=&d; // illegal
ptr=&b; // ok
ptr->f(); // calls B::f()
Standard conversions don’t
convert derived class pointers to
base class pointers with
private/protected derivation.
Always use public inheritance
with polymorphism.
174
©Copyright 2004, Cognizant Academy, All Rights Reserved
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.
175
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Function Implementation contd…
Base Members
vptr
Base b1;
Derived d1;
Base Members
vptr
Derived Members
Base vtbl;
Derived vtbl;
Base::f1()
Base::f2()
Base::f3()
Base::f1()
Derived::f2()
Base::f3()
Derived::f4()
176
©Copyright 2004, Cognizant Academy, All Rights Reserved
Virtual Function – Example 4
class Base{
public :
Base() { }
virtual void f1() { cout<<”base::f1( )” << endl; }
virtual void f2( ) { cout << Base:: f2()”<<endl; }
virtual void f3() { cout<<”Base :: f3()”<<endl; }
};
class Derived {
public:
Derived() { }
void f2() { cout<<”Derived ::f2()”<<endl; }
virtual void f4() { cout<<Derived ::f4()”<,endl;}
};
Base b1;
Derived d1;
Base *p=&d1;
p->f4(); // illegal
Derived *q=&d1;
q->f4() ;// legal
With the help of base
class pointer, we can’t
access any derived
class members.
177
©Copyright 2004, Cognizant Academy, All Rights Reserved
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 Bertrand Mayer
All
PDF http://www.kbcafe.com/articles/OOP.
Concepts.pdf
All
URL http://www.desy.de/gna/html/cc/Tutor
ial/tutorial.html
All
http://www.bitpipe.com/rlist/term/Obj
ect-Oriented-Programming.html
All
http://www.well.com/user/ritchie/oo.h
tml
All
http://www.planetpdf.com/codecuts/p
dfs/ooc.pdf
All
Congratulations!
You have successfully
completed
Object Oriented
Programming

More Related Content

Similar to 16613874-Object-Oriented-Programming-Presentation.ppt

Machine Learning in Software Engineering
Machine Learning in Software EngineeringMachine Learning in Software Engineering
Machine Learning in Software EngineeringAlaa Hamouda
 
01 zero lecture lovely professional university CSE111.pptx
01 zero lecture lovely professional university CSE111.pptx01 zero lecture lovely professional university CSE111.pptx
01 zero lecture lovely professional university CSE111.pptxmexebi1971
 
Lesson 1 - Object Oriented Programming CPP103.pptx
Lesson 1 - Object Oriented Programming CPP103.pptxLesson 1 - Object Oriented Programming CPP103.pptx
Lesson 1 - Object Oriented Programming CPP103.pptxLuiFlor
 
Design Engineering and Design concepts
Design Engineering and Design conceptsDesign Engineering and Design concepts
Design Engineering and Design conceptsJigyasaAgrawal7
 
Uc14 chap13
Uc14 chap13Uc14 chap13
Uc14 chap13ayahye
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Programming language paradigms
Programming language paradigmsProgramming language paradigms
Programming language paradigmsAshok Raj
 
.net Based Component Technologies
.net Based Component Technologies.net Based Component Technologies
.net Based Component Technologiesprakashk453625
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examplesAbdii Rashid
 
5_6134023428304274682.pptx
5_6134023428304274682.pptx5_6134023428304274682.pptx
5_6134023428304274682.pptxgamingpro22
 
HOW TO PHYSICALLY DESIGN A COMPUTER BASED INFORMATION SYSTEM
HOW TO PHYSICALLY DESIGN A COMPUTER BASED INFORMATION SYSTEMHOW TO PHYSICALLY DESIGN A COMPUTER BASED INFORMATION SYSTEM
HOW TO PHYSICALLY DESIGN A COMPUTER BASED INFORMATION SYSTEMRebekahSamuel2
 
Software Engineering- Crisis and Process Models
Software Engineering- Crisis and Process ModelsSoftware Engineering- Crisis and Process Models
Software Engineering- Crisis and Process ModelsNishu Rastogi
 

Similar to 16613874-Object-Oriented-Programming-Presentation.ppt (20)

Machine Learning in Software Engineering
Machine Learning in Software EngineeringMachine Learning in Software Engineering
Machine Learning in Software Engineering
 
01 zero lecture lovely professional university CSE111.pptx
01 zero lecture lovely professional university CSE111.pptx01 zero lecture lovely professional university CSE111.pptx
01 zero lecture lovely professional university CSE111.pptx
 
Oop.pptx
Oop.pptxOop.pptx
Oop.pptx
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++
 
Lesson 1 - Object Oriented Programming CPP103.pptx
Lesson 1 - Object Oriented Programming CPP103.pptxLesson 1 - Object Oriented Programming CPP103.pptx
Lesson 1 - Object Oriented Programming CPP103.pptx
 
Design Engineering and Design concepts
Design Engineering and Design conceptsDesign Engineering and Design concepts
Design Engineering and Design concepts
 
Uc14 chap13
Uc14 chap13Uc14 chap13
Uc14 chap13
 
Uc14 chap13
Uc14 chap13Uc14 chap13
Uc14 chap13
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Oop basic overview
Oop basic overviewOop basic overview
Oop basic overview
 
DE PPT.pptx
DE PPT.pptxDE PPT.pptx
DE PPT.pptx
 
Programming language paradigms
Programming language paradigmsProgramming language paradigms
Programming language paradigms
 
.net Based Component Technologies
.net Based Component Technologies.net Based Component Technologies
.net Based Component Technologies
 
DITEC - Software Engineering
DITEC - Software EngineeringDITEC - Software Engineering
DITEC - Software Engineering
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
 
5_6134023428304274682.pptx
5_6134023428304274682.pptx5_6134023428304274682.pptx
5_6134023428304274682.pptx
 
HOW TO PHYSICALLY DESIGN A COMPUTER BASED INFORMATION SYSTEM
HOW TO PHYSICALLY DESIGN A COMPUTER BASED INFORMATION SYSTEMHOW TO PHYSICALLY DESIGN A COMPUTER BASED INFORMATION SYSTEM
HOW TO PHYSICALLY DESIGN A COMPUTER BASED INFORMATION SYSTEM
 
Software Engineering- Crisis and Process Models
Software Engineering- Crisis and Process ModelsSoftware Engineering- Crisis and Process Models
Software Engineering- Crisis and Process Models
 
Reusability
ReusabilityReusability
Reusability
 
Lecture 5 reusability
Lecture 5 reusabilityLecture 5 reusability
Lecture 5 reusability
 

Recently uploaded

The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 

Recently uploaded (20)

Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 

16613874-Object-Oriented-Programming-Presentation.ppt

  • 2. 2 ©Copyright 2004, Cognizant Academy, All Rights Reserved About the Author Created By: Cognizant Academy Version and Date: OOPSCONCPT/PPT/0404/1.0
  • 3. 3 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 4. 4 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 Programming paradigms 2 OOPS Concepts 3 Functions in C++ 5 Inheritance 6 Polymorphism 4 Classes and Objects
  • 5. 5 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 6. 6 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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. Programming Paradigms : Overview
  • 7. 7 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 8. 8 ©Copyright 2004, Cognizant Academy, All Rights Reserved Procedural Programming Sub-programs Global data • 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)
  • 9. 9 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 10. 10 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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. Modules Global data Local Data Local Data Local Data Sub-programs
  • 11. 11 ©Copyright 2004, Cognizant Academy, All Rights Reserved • Three types of control flow are used: - sequence - selection - iteration Structured Programming Y/N
  • 12. 12 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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 Structured Programming
  • 13. 13 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 14. 14 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 15. 15 ©Copyright 2004, Cognizant Academy, All Rights Reserved  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 Oriented Programming Data variable Member Function Data variable Member Function Data variable Member Function Object A Object B Object C
  • 16. 16 ©Copyright 2004, Cognizant Academy, All Rights Reserved Object Oriented Programming • Does not deal with programming in the sense of developing algorithms or data-structures • Focuses on ADT
  • 17. 17 ©Copyright 2004, Cognizant Academy, All Rights Reserved POA Vs OOA Director Cell H/W Components Room Service Engineer Room System assembled with the supplied H/w components Send H/w + Instructions to assemble the system Fetch Components Procedure Oriented Approach:
  • 18. 18 ©Copyright 2004, Cognizant Academy, All Rights Reserved Object Oriented Approach:
  • 19. 19 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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)
  • 20. 20 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 21. 21 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 22. 22 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 23. 23 ©Copyright 2004, Cognizant Academy, All Rights Reserved Class & Object Account acct_no name balance withdraw() deposit( ) 431245 Patrick 50567.78 431246 Meyer 35567.78 Account:acct1 Account:acct2
  • 24. 24 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 25. 25 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 26. 26 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 27. 27 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 28. 28 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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. Data Abstraction
  • 29. 29 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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. Data Abstraction
  • 30. 30 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 31. 31 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 )
  • 32. 32 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 33. 33 ©Copyright 2004, Cognizant Academy, All Rights Reserved Inheritance Account acct_no name balance withdraw() deposit( ) Savings Acc interest Current Acc overdraft
  • 34. 34 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 35. 35 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 36. 36 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 };
  • 37. 37 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 38. 38 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 39. 39 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; }
  • 40. 40 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 }
  • 41. 41 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 42. 42 ©Copyright 2004, Cognizant Academy, All Rights Reserved Functions in C++ • References • Function Overloading • Default values • Inline Functions • Function Templates • Friend Functions • Static Members and Functions • Constant Functions and Constant data members
  • 43. 43 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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; } Parameter passing mechanisms
  • 44. 44 ©Copyright 2004, Cognizant Academy, All Rights Reserved • Call by value: another example main( ) { int x,y; //actual args void change(int,int); x=4; y=5; change(x, y); } void change(int a, int b) { //a,b formal args int k; k=a; a=b; b=k; } 4 x 5 y 5 a 4 b Parameter passing mechanisms
  • 45. 45 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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; } Parameter passing mechanisms
  • 46. 46 ©Copyright 2004, Cognizant Academy, All Rights Reserved • Call by address: another example main( ) { int x,y; //actual args void change(int *,int*); x=4; y=5; change(&x, &y); } void change(int *a, int *b) { //a,b formal args int *k; *k=*a; *a=*b; *b=*k; } 4 x 5 y Parameter passing mechanisms
  • 47. 47 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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; } Parameter passing mechanisms
  • 48. 48 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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. References Const pointer – Initialized to actualint cannot point to another variable int actualint = 123; int *const intptr = &actualint;
  • 49. 49 ©Copyright 2004, Cognizant Academy, All Rights Reserved • Value of a reference cannot be changed int actualint = 123; int &otherint = actualint; 123 actualint otherint otherint++ 124 otherint++ References & Constants int & const otherint = actualint; // Error Meaningless as all references are constants by definition
  • 50. 50 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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: DataType & ReferenceVariable = ValueVariable Standard or user defined data type: char, short, int, float, etc. Reference operator C++ alias variable C++ value variable
  • 51. 51 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 ref 1 count ref 2
  • 52. 52 ©Copyright 2004, Cognizant Academy, All Rights Reserved • Reference to a constant: Possible • Constant reference declaration: Not Possible int actualint = 123; const int &otherint = actualint; •readonly alias for actualint •can’t make any modification int & const otherint = actualint; // Error • Meaningless as all references are constants by definition References and pointers
  • 53. 53 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 54. 54 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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)
  • 55. 55 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.; } Function Overloading
  • 56. 56 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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); Function Overloading
  • 57. 57 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 58. 58 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 59. 59 ©Copyright 2004, Cognizant Academy, All Rights Reserved • Examples: // Declarations //Function calls int add(int a, int b); // prototype 1 int add(int a, int b, int c); // prototype 2 double add(double x, double y) // prototype 3 double add(int p, double q) // prototype 5 double add(double p,int q) // prototype 5 cout<<add(15,10); cout<<add(15,10.5); cout<<add(15.5,10.5); cout<<add(15,10,5); cout<<add(0.15,1.05); Default Values
  • 60. 60 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 61. 61 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 62. 62 ©Copyright 2004, Cognizant Academy, All Rights Reserved Inline Functions inline ReturnType FunctionName(Parameters) { // Body of a main function } Keyword, function qualifier Syntax of inline function definition:
  • 63. 63 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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. inline int sqr(int num) { return num * num; } void main( ) { --- a=sqr(5); b=sqr(n); --- } void main( ) { --- a = 5 * 5; b = n * n; --- } preprocessor Inline Functions
  • 64. 64 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 65. 65 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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. Inline Functions versus Macros
  • 66. 66 ©Copyright 2004, Cognizant Academy, All Rights Reserved # define SQUARE(num) num * num inline float square(float j) { return (j * j); } void main( ) { int p=3,q=3,r,s; r=SQUARE(++p); s=square(++q); cout<<“r = “ << r << “s = “<<s; } Output r =25 s =16 Macro SQUARE( ) expands into r = ++num * ++num  In macro expansion num is incremented twice. Inline function square( )  var ‘q’ is incremented only once and is assigned to j then j * j. Inline Functions versus Macros
  • 67. 67 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 68. 68 ©Copyright 2004, Cognizant Academy, All Rights Reserved Static Members contd., • Static Data Members: Object A Object B Object C Static variable
  • 69. 69 ©Copyright 2004, Cognizant Academy, All Rights Reserved • Static Member Example class account { private: int currentBal; static int RateofInt; }; myclass A(0), B(1); currentBal=0 Object A Object B Shared by all objects Static Members contd., currentBal=1
  • 70. 70 ©Copyright 2004, Cognizant Academy, All Rights Reserved Static Members contd., • Static Data Members: class SavingsAccount { private: char name[30]; float total; float CurrentRate; public: SavingsAccount(); void EarnInterest() { total + = CurrentRate * total; } } Only one copy should be available as all objects should have same Interest rate Declare CurrentRate as static float CurrentRate; To make CurrentRate accessible to all objects
  • 71. 71 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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 Constant data member and Constant Functions
  • 72. 72 ©Copyright 2004, Cognizant Academy, All Rights Reserved • The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. • 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. int main() { const int i = 5; --- } Constant data member and Constant Functions
  • 73. 73 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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( ); --- } Constant data member and Constant Functions
  • 74. 74 ©Copyright 2004, Cognizant Academy, All Rights Reserved class Time { int hour; public: Time(int k) { hour=k; } void update( ) { hour++; } int value( ) const { return hour; } void cheat( ) const { hour++; } }; void main (void) { Time t(10); cout<<t.value( ); } // error this is const 11 Constant data member and Constant Functions
  • 75. 75 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 76. 76 ©Copyright 2004, Cognizant Academy, All Rights Reserved template < class identifier > ReturnType FunctionName(arguments of type identifier) Function Templates template < class T > // or template< typename T > T square( T value1 ) { return value1 * value1; } Keyword for declaring function template Keyword class Name of the template data-type Function parameters of type template, primitive or user-defined
  • 77. 77 ©Copyright 2004, Cognizant Academy, All Rights Reserved Examples: Convert function to convert a float Fahrenheit temperature to Celsius Function Templates 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.; }
  • 78. 78 ©Copyright 2004, Cognizant Academy, All Rights Reserved Function Templates // definition of function template maximum template < class T > // or template < typename T > T maximum( T value1, T value2, T value3 ) { T max = value1; if ( value2 > max ) max = value2; if ( value3 > max ) max = value3; return max; } maximum( int1, int2, int3 ) maximum( double1, double2, double3 ) maximum( char1, char2, char3 ) In main( ) 1, 2, 3 1.1 , 2.1, 1.8 A, B,C Input values 3 2.1 C Output Maximum value
  • 79. 79 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 80. 80 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 81. 81 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 82. 82 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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).
  • 83. 83 ©Copyright 2004, Cognizant Academy, All Rights Reserved Constructors contd., class sum { public: int x, y; sum( ); }; sum::sum(void) { cout<<" Inside sum( )n"; x=2;y=4; // if not initialized garbage } void main( ) { sum s; cout<<"Inside main( )n"; cout<<"x= " << s.x<<"y= "<<s.y; } Inside sum( ) Inside main( ) x= 2 y= 4 Constructor declared Object created and initialized by constructor Constructor defined Object s x= 2 y= 4
  • 84. 84 ©Copyright 2004, Cognizant Academy, All Rights Reserved Constructors with arguments • Parameters can be passed to the constructors class sum { public: int x, y; sum(int i,int j); }; sum::sum(int i,int j) { x=i;y=j; } void main( ) { sum s1(10,20); sum s2 = sum(30,40); cout<<"x= " << s1.x<<"y= "<<s1.y; cout<<"x= " << s2.x<<"y= "<<s2.y; } x= 10 y= 20 Parameterized Constructor Object s1 Object s2 x= 30 y= 40 Constructor called implicitly
  • 85. 85 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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;}; sum(int, int) {x=i;y=j;}; sum(sum & i) {x=i.x;y=i.y;}; Two arguments Copy constructor No arguments
  • 86. 86 ©Copyright 2004, Cognizant Academy, All Rights Reserved Constructors with default arguments • Constructors can be defined with default arguments class sum { public: int x, y; sum(int i, int j=10); }; sum::sum(int i,int j) {x=i;y=j;} void main() { 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; } x= 1 y= 10 Object s1 Object s2 x= 8 y= 9 Default value for j=10 (Used by the object s1)
  • 87. 87 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 88. 88 ©Copyright 2004, Cognizant Academy, All Rights Reserved Copy Constructors contd., class sum { public: int x; sum(){ } sum(int i) {x=i;} sum(sum &j) {x=j.x;} }; void main() { sum s1(10); sum s2(s1); sum s3=s1; sum s4; 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 x=10 x=10 x=10 x=10 s1 s2 s3 s4
  • 89. 89 ©Copyright 2004, Cognizant Academy, All Rights Reserved #include<string.h> class String { char* data; public: String(const char* s = "") { 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() { cout << data; } }; int main() { String s = "hello"; // same as String s("hello"); cout <<”s=”<<s.display( ); String empty; cout<<”empty=”<<empty.display(); } s = hello empty= Copy Constructors contd.,
  • 90. 90 ©Copyright 2004, Cognizant Academy, All Rights Reserved int main() { String s = "hello"; String t = s; // same as String t(s); s.display( ); t.display( ); t.assign(“world”); s.display( ); t.display( ); } hello hello world world hello0 data data Copy Constructors contd., Shallow Copy
  • 91. 91 ©Copyright 2004, Cognizant Academy, All Rights Reserved String(const String& s) { data = new char[strlen(s.data)+1]; strcpy(data, s.data); } Deep Copy Deep copy hello0 data data hello0 Copy Constructors contd.,
  • 92. 92 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 93. 93 ©Copyright 2004, Cognizant Academy, All Rights Reserved Destructors contd., Declaration – Same name as class • Preceded with tilde (~) ~sum( ) { }
  • 94. 94 ©Copyright 2004, Cognizant Academy, All Rights Reserved Constant Objects const objects using const keyword before object declaration. For example: const sample s ( m, n); // object s is constant
  • 95. 95 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 96. 96 ©Copyright 2004, Cognizant Academy, All Rights Reserved Static Object Example #include<iostream.h> class account { int acc_no; public: account() {cout<<"Account constructor"; } ~account() {cout<<"Account desctructor"; } }; void create_stobj() { account vip; } void main(void) { clrscr(); account acc1; create_stobj(); getch(); } Account constructor Account constructor Account destructor Account constructor Account constructor
  • 97. 97 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 98. 98 ©Copyright 2004, Cognizant Academy, All Rights Reserved #include <iostream.h> class two { int a,b; public: void let(int x, int y) { a=x; b=y; } void print(void) {cout<<"a="<<a<<" b="<<b; } void assign(one x) { a=x.a1; b=x.b1; } }; class one int a1,b1; public: one(void) { a1=5, b1=10; } friend class two; }; void main(void) { one o1; two t1; t1.let(4,2); t1.print(); t1.assign(o1); t1.print(); } a = 4 b= 2 a= 5 b=10 Friend class example
  • 99. 99 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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( ); y.sum(2.2, 3.7); y.print( ); } The sum is : 5 The sum is : 5.9
  • 100. 100 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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. 4. Inheritance
  • 101. 101 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 102. 102 ©Copyright 2004, Cognizant Academy, All Rights Reserved Inheritance Student Reg.No. Course Marks Teaching Staff Edn.Qual. Designation Specialization Person Name Sex Age “Person” is a generalization of “Student”. “Student” is a specialization of “Person”.
  • 103. 103 ©Copyright 2004, Cognizant Academy, All Rights Reserved Defining Derived Class • The general form of deriving a subclass from a base class is as follows • 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. Class derived-class-name : visibility-mode base-class-name { ……………… // ……………….// members of the derived class };
  • 104. 104 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 105. 105 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 Person Student subclass(derived class) superclass(base class) class Person { ….. }; class Student : public Person { ………… }; visibility mode
  • 106. 106 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 Student CS -Student Class Person { ……}; Class Student : public Person { ……}; Class CS -Student : public Student { …….};
  • 107. 107 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 Part-time Student Class Employee {……..}; Class Student {……..}; Class Part-time Student : public Employee, public Student {…….};
  • 108. 108 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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. Person Student Employee Class Person {……}; Class Student : public Person {……}; Class Employee : public Person {……};
  • 109. 109 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 Student PG - Student Gate Score Class Person { ……}; Class Student : public Person { ……}; Class Gate Score {…….}; Class PG - Student : public Student public Gate Score {………};
  • 110. 110 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 111. 111 ©Copyright 2004, Cognizant Academy, All Rights Reserved Person Student Employee Part-time Student Virtual Inheritance Class Person {……}; Class Student : public Person {……}; Class Employee : public Person {……}; Class Part-time Student : public Student, public Employee {…….};
  • 112. 112 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 113. 113 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 114. 114 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 115. 115 ©Copyright 2004, Cognizant Academy, All Rights Reserved Access Specifiers with Inheritance Class X { int priv; protected: int prot; public: int publ; void m( ); }; void X::m( ) { priv =1; //Ok prot =1; //Ok publ =1; //Ok } class Y : public X { void mderived( ); } Y::mderived( ) { priv =1; //Error priv is private and //cannot be inherited prot =2; // Ok publ=3; // Ok } void global_fun(Y *p) { p->priv = 1; //Error : priv is //private of X p->prot = 2; //Error : prot is //protected and the function global_fun( ) // is not a friend or a member of X or Y p->publ =3; // Ok }
  • 116. 116 ©Copyright 2004, Cognizant Academy, All Rights Reserved Public, Protected and Private derivation private : int a1; protected : int a2; public : int a3; private : int b1; protected : int b2; public : int b3; private : int b1; protected: int a2; int b2 public: int b3;int a3; Public Derivation Class A Class B Class B: Public A
  • 117. 117 ©Copyright 2004, Cognizant Academy, All Rights Reserved Public derivation - example class A { private : int a; protected: int b; public : void get_a( ) { cin>>a;} void get_b( ) { cin>>b;} void print_a( ) { cout<<a;} void print_b( ) {cout<<b;} }; 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; } }; void main( ) { B b1; b1.get_a( ); b1.get_b( ); b1.get_c( ); b1.get_d( ); b1.print_all( ); }
  • 118. 118 ©Copyright 2004, Cognizant Academy, All Rights Reserved Protected derivation - example private : int a1; protected : int a2; public : int a3; private : int b1; protected : int b2; public : int b3; private : int b1; protected: int a2; int b2,a3; public: int b3; Protected Derivation • 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
  • 119. 119 ©Copyright 2004, Cognizant Academy, All Rights Reserved Protected derivation - example class A { private: int a; protected: int b; public : void get_a( ) { cin>>a;} void get_b( ) { cin>>b;} void print_a( ) { cout<<a;} void print_b( ) {cout<<b;} }; class B : protected A { 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;}; } void main( ) { B b1; b1.get_a( ); //ERROR b1.get_b( ); //ERROR b1.get_ab( ); b1.get_c( ); b1.get_d( ); b1.print_all( ); }
  • 120. 120 ©Copyright 2004, Cognizant Academy, All Rights Reserved Private derivation - example The inherited public and protected members of a private derivation become private members of the derived class. private : int a1; protected : int a2; public : int a3; private : int b1; protected : int b2; public : int b3; private : int b1; int a2,a3; protected: int b2; public: int b3; Private Derivation Class A Class B Class B : private A
  • 121. 121 ©Copyright 2004, Cognizant Academy, All Rights Reserved Private derivation - example class A { private: int a; protected: int b; public : void get_a( ) { cin>>a;} void get_b( ) { cin>>b;} void print_a( ) { cout<<a;} void print_b( ) {cout<<b;} }; class B : private A { 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_abcd( ) { print_a( ); cout<<b<<c<<d; } }; Class C : public B { public : void get_all( ) { get_a( ); //ERROR get_b( ); //ERROR get_ab( ); //Ok get_c( ); //Ok get_d( ); //Ok } void print_all( ) { print_a( ); //ERROR print_b( ); //ERROR print_cd( ); //Ok print_abcd( ); //Ok } }; void main( ) { C c1; c1.get_a( ); //ERROR c1.get_b( ); //ERROR c1.get_c( ); // Ok c1.get_d( ); //Ok c1.getall( ); //Ok c1.print_all( ); //Ok }
  • 122. 122 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 123. 123 ©Copyright 2004, Cognizant Academy, All Rights Reserved Derived Class Constructors class B { int x; public : B( ) { cout<<”B::B( ) Fires…”<<endl;} }; class D : public B { int y; public : D( ) { cout<<”D::D( ) Fires…”<<endl;} }; void main( ) { D d; } B::B( ) Fires… D::D( ) Fires…
  • 124. 124 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; public : D( ) { b =0; cout<<”D::D( ) Fires…”<<endl;} D(int x) { b =x; cout<<”D::D(int) Fires…”<<endl;} D(int x, int y) : B(y) { b =x; cout<<”D::D(int, int) Fires…”<<endl;} }; void main( ) { D d; D d(10); D d(10, 20); } B::B( ) Fires… D::D( ) Fires… B::B( ) Fires… D::D(int) Fires… B::B(int) Fires… D::D(int, int) Fires…
  • 125. 125 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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;} }; class D : public B { int y; public : D( ) { cout<<”D Constructor Invoked …”<<endl;} ~ D( ) { cout<<”D Destructor Invoked…”<<endl;} }; void main( ) { D d; } B Constructor Invoked… D Constructor Invoked… D Destructor Invoked… B Destructor Invoked …
  • 126. 126 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 { protected : int a; public : void getdata( ) { cin>>a;} void putdata( ) { cout << a;} }; class B : public A { protected: int b; public : void getdata( ) { cin>>a>>b;} void putdata( ) { cout<<a<<b;} }; void main( ) { B b1; b1.getdata( ); // B::getdata( ) //is invoked b1.putdata( ); // B::putdata( ) //is invoked b1.A::getdata( ); // A::getdata( ) // is invoked b1.A::putdata( ); // A::putdata( ) //is invoked }
  • 127. 127 ©Copyright 2004, Cognizant Academy, All Rights Reserved Composition class x { int i; public: x() {i=0;} void set(int j) { i=j;} int read() const { return i;} }; class y { int i; public: X x; Y() { i=0;} void f(intj) { i=j;} int g() const { return i;} }; int main() { Y y; y.f(5); y.x.set(10); } • Classes having objects of other classes as their data members - composite classes
  • 128. 128 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 129. 129 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 130. 130 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 131. 131 ©Copyright 2004, Cognizant Academy, All Rights Reserved Types of polymorphism Polymorphism Operator Overloading Function Overloading Static Polymorphism Dynamic Polymorphism Virtual Fucntion
  • 132. 132 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 133. 133 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 134. 134 ©Copyright 2004, Cognizant Academy, All Rights Reserved • To overload means give it an additional meaning. • Function definition syntax for operator overloading Operator overloading
  • 135. 135 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 136. 136 ©Copyright 2004, Cognizant Academy, All Rights Reserved Operator Overloading • Syntax of Operator overloading FRIEND function • Number of arguments in a friend function for • Unary operator – 1 • Binary operator – 2 ReturnType operator OperatorSymbol (argument list) { Function body } Keyword Operator to be overloaded
  • 137. 137 ©Copyright 2004, Cognizant Academy, All Rights Reserved Operator Overloading • Syntax of Operator overloading Class Member • Number of arguments in a member function for • Unary operator – 0 • Binary operator – 1 ReturnType classname :: OperatorSymbol (argument list) { Function body } Operator to be overloaded
  • 138. 138 ©Copyright 2004, Cognizant Academy, All Rights Reserved • Operators that can not be overloaded Operator Overloading ∙ ٫ → ?: sizeof Operators that can be overloaded + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[]
  • 139. 139 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 )
  • 140. 140 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; };
  • 141. 141 ©Copyright 2004, Cognizant Academy, All Rights Reserved // 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; } Unary Operators Overloading
  • 142. 142 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 • The same operators can be defined in file scope (globally) using the following function heads: Unary Operators Overloading
  • 143. 143 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 )
  • 144. 144 ©Copyright 2004, Cognizant Academy, All Rights Reserved Binary Operator Overloading class Point { public: int x,y; Point () {}; Point (int,int); Point operator + (Point); }; Point::Point (int a, int b) { x = a; y = b; } Point Point::operator+ (Point P) { Point temp; temp.x = x + P.x; temp.y = y + P.y; return (temp); } int main () { Point a (3,1); Point b (1,2); Point c; c = a + b; // c=a.operator+(b); cout << c.x << "," << c.y; return 0; } 2,3
  • 145. 145 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 146. 146 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.} Assignment operator overloading
  • 147. 147 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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
  • 148. 148 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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); return 0; } //c=b+d
  • 149. 149 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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 Non-member operators
  • 150. 150 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; }
  • 151. 151 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 required Conversion takes palce in Source class Conversion takes palce in Destination class Basic class Not applicable Constructor Class basic Casting Operator Not Applicable Class class Casting operator Constructor
  • 152. 152 ©Copyright 2004, Cognizant Academy, All Rights Reserved // spec1_conversion_functions2.cpp // C2666 expected #include <string.h> class String { public: // Define constructor that converts //from type char * String( char *s ) { strcpy( _text, s ); } // Define operator conversion function //to type char * operator char *() { return _text; } int operator==( const String &s ) { return !strcmp( _text, s._text ); } private: char _text[80]; }; int main() { String s( "abcd" ); char *ch = "efgh"; // Cause the compiler to //select a conversion. return s == ch; } Type Conversion The compiler has two choices and no way of determining which is correct. (i)It can convert ch to an object of type String using the constructor and then perform the comparison using the user-defined operator==. (ii)It can convert s to a pointer of type char * using the conversion function and then perform a comparison of the pointers.
  • 153. 153 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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. Operator Overloading
  • 154. 154 ©Copyright 2004, Cognizant Academy, All Rights Reserved • 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. Operator Overloading
  • 155. 155 ©Copyright 2004, Cognizant Academy, All Rights Reserved Polymorphism : Non–Virtual Functions class B{ public: void f(); }; class D: public B{ public: // f() not overridden }; void main(){ D d B*bp=&d; D*pd=&d; d.f(); // B::f() pb->f(); //B::f() pd->f(); // B::f() } No matters style of call, function name and object type serve as basics for function body selection. All three calls of f( ) on derived class object d through the object, through a base class pointer and through a derived class pointer provides the same result.
  • 156. 156 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 157. 157 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } };
  • 158. 158 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } };
  • 159. 159 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Functions : Example 1 contd… int main() { One one ; Two two; Three three; One * array[3]; array[0]=&one; array[1]=&two; array[2]=&three; for(int i=0;i<3;i++) array[i]->whoami(); return EXIT_SUCCESS; } The Output is One One One
  • 160. 160 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 161. 161 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Functions : Example 2 Class B { int x; public: virtual void g(); int h(); }; class D : public B { int y; public: void g(); int h(); }; int main() { D d; B *ptr = &d; ptr->h(); B::h invoked ptr->g(); D::h invoked }
  • 162. 162 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Functions : Example 3 class Base { public: virtual void fun(){ cout<<”This is base fun().n”; } }; class Derived0 : public Base{ public: void fun(){ cout<<” This is derived0 fun(). n”;} }; class Derived1 : public Base{ public: void fun(){ cout<<” This is derived1 fun() . n”; } }; int main() { Base *ptr B; Derived0 D0; Derived1 D1; ptr=&B; ptr->fun(); ptr=&D0; ptr->fun(); ptr=&D1; p->fun(); return 0; }
  • 163. 163 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Functions : Example 3 contd.. Output This is base fun() This is derive0 fun() This is derive1 fun()
  • 164. 164 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 165. 165 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Functions : Constructors contd… class B { public: B( ) { this->f(); } virtual void f() { cout<<”Executing B::f()”<<endln; } }; class D: public B { public: D( ){ } virtual void f( ) { cout<<”Executing D::f()”<<endl; } }; main() { D d; cout<<”object d was created successfully”<<endl; d.f(); } output Executing B::f() object d created successfully. Executing D::f()
  • 166. 166 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } };
  • 167. 167 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } };
  • 168. 168 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Functions : Destructors contd… int main(){ const int forever =1; void f(); while(forever) f(); return EXIT_SUCCESS; } void f(){ B*p=new D; delete p; } The Memory will be exhausted, in each call of function f( ), B allocates 5 bytes D allocates 1000 bytes B frees 5 bytes. As p is of type B*, p is bound to B’s data members and methods, including constructors and destructors rather than to D’s methods . When f exits B::~B frees the 5 bytes. D::~D() fails to fire.
  • 169. 169 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } };
  • 170. 170 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Function : Default Arguments contd… int main () { Derived *pd=new derived; Base *pb=pd; int val = pb->foo(); cout<<”main : val through base “ <<val<<endl; val = pd->foo(); 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 The default argument to be passed to foo() is not determined at run time, rather it is determined at compile time and is based on the type of the object through which the function is being invoked.
  • 171. 171 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 172. 172 ©Copyright 2004, Cognizant Academy, All Rights Reserved Pure Virtual Function class Base { public: virtual void show()=0 // Pure Virtual function }; class Derv1 : public Base { public: void show(){ cout<<”n Derv 1”; } }; class Derv2 : public Base{ public: void show(){cout<<”n In Derv2”; } }; void main(){ Base *List[2]; Derv1 dv1; Derv2 dv2; List[0]=&dv1; List[1]=&dv2; List[0]->show(); List[1]->show(); }
  • 173. 173 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Function & Private/Protected Derivation Polymorphism does not work with private or protected derivation class Base{ public: virtual void f(); }; class Derived : private Base{ public: void f(); }; Base *ptr, b; Derived d; ptr=&d; // illegal ptr=&b; // ok ptr->f(); // calls B::f() Standard conversions don’t convert derived class pointers to base class pointers with private/protected derivation. Always use public inheritance with polymorphism.
  • 174. 174 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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.
  • 175. 175 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Function Implementation contd… Base Members vptr Base b1; Derived d1; Base Members vptr Derived Members Base vtbl; Derived vtbl; Base::f1() Base::f2() Base::f3() Base::f1() Derived::f2() Base::f3() Derived::f4()
  • 176. 176 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Function – Example 4 class Base{ public : Base() { } virtual void f1() { cout<<”base::f1( )” << endl; } virtual void f2( ) { cout << Base:: f2()”<<endl; } virtual void f3() { cout<<”Base :: f3()”<<endl; } }; class Derived { public: Derived() { } void f2() { cout<<”Derived ::f2()”<<endl; } virtual void f4() { cout<<Derived ::f4()”<,endl;} }; Base b1; Derived d1; Base *p=&d1; p->f4(); // illegal Derived *q=&d1; q->f4() ;// legal With the help of base class pointer, we can’t access any derived class members.
  • 177. 177 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 Bertrand Mayer All PDF http://www.kbcafe.com/articles/OOP. Concepts.pdf All URL http://www.desy.de/gna/html/cc/Tutor ial/tutorial.html All http://www.bitpipe.com/rlist/term/Obj ect-Oriented-Programming.html All http://www.well.com/user/ritchie/oo.h tml All http://www.planetpdf.com/codecuts/p dfs/ooc.pdf All