View
20
Download
0
Category
Preview:
Citation preview
OBJECT ORIENTED
TECHNIQUES
MODULE I
Fundamentals of Object Oriented
Design
Procedure Oriented Programming In POP the main program is divided
into a number of functions. In a multi-function program many
important data items are placed as global.
Global data are vulnerable to an inadvertent change by a function.
Another drawback of POP is that it does not model real world entities well.
POP employs does top-down approach.
Structure of POP
Main Program
Function - 2 Function - 3Function - 1
Function - 4 Function - 5
Function - 6 Function - 7 Function - 8
Relationship of data and functions in POP
Global Data Global Data
Function - 1 Function - 2 Function - 3
Local Data Local Data Local Data
Object-Oriented ProgrammingOOP decomposes a problem into a number
of entities called objects and then build data and functions around these objects.
Functions that operate on data of an object are tied together in that object.
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through functions.
OOP continue…
New data and functions can be added whenever necessary.
Follows bottom-up approach in program design.
Organization of data and functions in OOP
Object A Object B
Communication
Object C
Data
Functions
Functions
Data
Functions
Data
Basic Concepts of OOP
ObjectsClassesData Abstraction EncapsulationInheritancePolymorphism
1.Objects
Objects are the basic run-time entities in object-oriented
design.E.g.:- a person, a place, a bank
accountDuring execution the objects interact by sending messages.
An object is an instantiation of a class.
In terms of variables, a class would be the type, and an object would be the variable.
Representation of an object
StudentObject: STUDENT
DATANameDate-of-birthMarks
FUNCTIONSTotalAverageDisplay
Total
Average
Display
2. ClassesA class is a collection of data and its
associated functions referenced under one name.
It is actually a collection of objects of the same type.
E.g.:- fruit is a class apple, orange etc are objects
of the class fruit
3. EncapsulationThe wrapping up of data and its
associated functions into a single unit (class) is called encapsulation.
The data is not accessible to the outside world.
This insulation of data from direct access by the program is called data hiding or information hiding.
4. Abstraction
Abstraction refers to the act of representing the essential features without including the background details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as wait, size ,cost ….
Functions operate on these attributes
The attributes are sometimes called data members because they hold information.
The functions that operate on these data are sometimes called methods or member functions.
Since the classes use the concept of data abstraction, they are known as abstract data type (ADT)
5. Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
It supports the concept of hierarchical classification.
Each derived class shares common characteristics with the class from which it is derived.
Property inheritance
BirdsAttributesFeathersLay eggs
Flying bird
Attributes.................………………
Attributes………………..……………….
Attributes……………………………….
Attributes………………………………
Attributes………………………………
Attributes……………….……………….
Nonflying bird
Parrot Peacock Penguin Kiwi
Inheritance provides the idea of reusability.
We can add additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing one.
The new class will have the combined feature of both the classes.
6. Polymorphism Polymorphism means ability to take more
than one form.
An operator exhibits different behavior in different instances depending on the types of its operands – operator overloading
The behavior of operator depends upon the types of data used in the program.
E.g. :- operator + case 1 :- 3 + 4 = 7
case 2 :- “abc” + “xyz” = “abcxyz”
Polymorphism continue…Using a single function name to
perform different types of tasks – function overloading
Shape
Circle object
Draw( circle)
Box object
Draw( box)
Square object
Draw (square)
Draw( )
Class hierarchiesA class that is inherited is referred
to as a base class.The class that does the inheriting is
called the derived class.• Single inheritance• Multilevel inheritance• Multiple inheritance• Hierarchical inheritance• Hybrid inheritance
Designing an Object-oriented system
Identify the classesAssign attributes and behaviorFind relationships between the
classesArrange the classes into
hierarchies
Identify the classes
One way is to look for nouns in the problem description
Identify the classes if physical entities are part of the problem description
Other potential classes are one’s to represent events and interactions
Assign attributes & behavior
Here, consider the responsibilities of the classes identified
Decide what its attributes will be and what operations are performed on it or by it
We need to consider what role the class plays in relation to the whole system
If one class is accepting an unfair share of responsibilities, it may be appropriate to split it.
We need to ensure the balance of responsibility amongst classes.
If a class has no responsibilities it should be discarded.
Having identified responsibilities for class, this leads up to modeling the behavior of a class.
Find relationship between the classes
• Association represents the relationship between objects and classes.
• The most common relationships between classes are:
Use (client-server association)Containment(“has-a”)(Aggregation) Inheritance(“is-a-kind-of”)
Arrange the classes into hierarchies
This stage is an extension of the first design step.
Step 2&3 have furnished us with further information, that will help us to identify hierarchies.
By assigning attributes and behaviors to classes in step 2, we will develop a closer idea of their similarities and differences.
By identifying the relationships of step3,we see which classes need to incorporate the functionality of others.
A first look at C++
What is C++ ?C++ is an OOP language. It was developed by Bjarne StroustrupC++ is an extension of CThe important facilities that C++ adds
to C areclassesinheritanceoperator overloadingfunction overloading
A Simple C++ program
#include<iostream.h>#include<conio.h>void main(){
clrscr();cout<<“C++ is better than C \n”;getch();
}
Output operator – cout<<
The identifier cout is a predefined object that represents the standard o/p stream (screen).
The operator << is called insertion or put to operator.
It sends the contents of the variable on its right to the object on its left.
The header file iostream should be included at the beginning of all programs that uses i/o statements
Output using insertion operator
Screen
cout << “C++ is better than C”
Program to add two numbers#include<iostream.h>#include<conio.h>void main(){
clrscr();int a, b, sum;cout<<“enter 2 numbers”;cin>>a;cin>>b;sum= a+b;cout<<“the sum =“<<sum;getch();
}
Input operator – cin>>The identifier cin is a predefined object
in C++ that corresponds to standard i/p stream (keyboard).
The operator >> is known as extraction or get from operator.
It extracts the value from the keyboard and assigns it to the variable on its right.
Input using extraction operator
keyboard
cin >> a
Cascading of I/O operators
The multiple use of << or >> in one statement is called cascading of I/O operators
E.g. :-cout<<“sum is “<<sum;cin>>a>>b;
C++ enhancements to C
Default Function Arguments
A function can be called without specifying all its arguments.
In such cases, the function assigns a default value to the parameter which does not have a matching argument in function call.
Default values are specified during function declaration.
Default arguments continue……
E.g. :-float amount(float principal, int period, float rate=0.15);
Suppose the function call is value = amount(5000,7);
Here one argument is missing and hence the default value is used for the argument rate.
Default arguments continue……
value = amount(5000,5,0.12);
passes an explicit value of 0.12 to rate.
An argument can be assigned a default value only if all the arguments on its right have default values.
Default arguments continue……
int add(int i, int j=5, int k=10); legal
int add(int i=5, int j, int k=10); illegal
int add(int i, int j, int k=10); legal
int add(int i=10, int j, int k); illegal
Placement of variable declarationsIn C all variables must be declared
before they are used in executable statements (at the beginning of scope).
But C++ allows the declaration of a variable anywhere in the scope.
This means that a variable can be declared right at the place of its first use.
Variable declarations continue……
#include<iostream.h>#include<conio.h>void main(){
clrscr();int n, a[100],sum=0,i;cout<<“enter the limit”;cin>>n;cout<<“enter the numbers”;
for(i=0; i<n; i++){cin>>a[i];sum= sum+a[i];}float avg = sum/n;cout<<“Sum=“<<sum;cout<<“Avg=“<<avg;getch();
}
Scope Resolution OperatorThe scope of a variable extends from
the point of its declaration till the end of the block containing the declaration.
A variable declared inside a block is said to be local to that block.
A variable declared outside all the blocks is said to be global variable.
Scope Resolution Operator continue……
…….…….{
int x = 10;…….…….
}…………{
int x = 1;…….…….
}
…….…….{
int x = 10; Block 1…….……. {int x = 1;……. Block 2…….}…………
}
Scope Resolution Operator continue……
In C++ the global version of a variable can be accessed from within the inner block using Scope Resolution Operator.
It can be used to uncover a hidden variable.
The general format is::variable-name
Scope Resolution Operator continue……
#include<iostream.h>#include<conio.h>int m=10;void main(){
clrscr();int m=20;{int k=m;int m=30;cout<<“inner block”;cout<<“k=“<<k;cout<<“m=“<<m;cout<<“::m=“<<::m;}
cout<<“outer block”;
cout<<“m=“<<m;cout<<“ ::m = “<< ::m;getch()
}Output
Inner block k=20 m=30::m=10
Outer block m=20::m=10
Namespace This defines a scope for the identifiers that
are used in a program. Eg. Using namespace std; Here std is the namespace where ANSI C++
standard class libraries are identified. All ANSI C++ programs must include this
directive. This will bring all the identifiers defined in
std to the current global scope. Using and namespace are the new
keywords of C++.
“const” qualifierThe qualifier const is used to create
symbolic constants in C++.E.g. :-
const int n=100;int a[n]; // invalid in C
The qualifier const allows us to create typed constants instead of having #define that creates constants that have no type information.
“const” qualifier continue……
If we use const qualifier alone it defaults int.const size = 100; meansconst int size = 100;
C++ requires const to be initializedThe scope of a const value is local to
the file where it is declared.To give a const value an external
linkage we must explicitly define it as extern in C++.extern const total = 1000;
Function overloadingThe use of the same function name
to create functions that perform a variety of different tasks - Function overloading.
We can define a family of functions with one function name but with different argument lists.
The correct function to be invoked is determined by checking the number and type of the arguments and not on function type.
Function overloading continue……
E.g. :- overloaded add() function
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 4
double add(double p, int q); //prototype 5
Function overloading continue……
// function callscout<<add(5,10); // uses
prototype 1
cout<<add(15,10.0); // uses prototype 4
cout<<add(12.5,7.5); // uses prototype 3
cout<<add(5,10,15); // uses prototype 2
cout<<add(0.75,10); // uses prototype 5
Function overloading continue……
A function call matches the prototype having the same number and type of arguments and then calls the appropriate function for execution.
The function selection involves the following steps.1. The compiler first tries to find an exact match.
Function overloading continue……
2. If an exact match is not found, the compiler uses integral promotions to the actual arguments.char to intfloat to double3. When either of them fails, the compiler tries to use the built-in-conversions to actual arguments If the conversion is possible to have a multiple match then the compiler will generate an error message.
Function overloading continue……
Suppose we use the following two functions:long square(long n);double square(double x);A function call such assquare(10)will cause an error because int argument can be converted to either long or double thereby creating ambiguous situations
Function overloading continue……
4. If all the steps fail then the compiler will try the user-defined conversions in combination with integral promotions and built in conversions.
Function overloading continue……
#include <iostream.h> void print(int i) {
cout << " Here is int " << i << endl;
} void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char c) {
cout << " Here is char" << c << endl;
} void main() {
print(10); print(10.10); print(“X");
}
Function overloading continue……
Eg.//Function volume() is overloaded
three times#include(iostream.h>using namespace std;//Declarations (prototypes)Int volume(int);double volume(double, int);long volume(long, int, int);Int main(){cout<<volume(10)<<“\n”;cout<<volume(2.5,8),,”\n”;cout<<volume(100L,75,15)<<“\n”;return 0;}
//Function definitionsint volume(int s) //cube{ return (s*s*s);}double volume(double r, int h)
//cylinder{ return(3.14519*r*r*h);}long volume(long l, int b, int h) //rectangular box{ return(l*b*h);}
Inline functionsAn inline function is a function that can
be expanded in line when it is invoked.The compiler replaces the function call
with the function code. Inline functions are defined as follows.
inline function-header{function body}
Inline functions continue……..E.g.:-
inline double cube(double a){return(a*a*a);}
The above function can be invoked by statements likec = cube(3.0);d = cube(2.5+1.5);
Inline functions continue……..
All inline functions must be defined before they are called.The speed benefits of inline functions diminish as the function grows in size.Usually, the functions are made inline when they are small enough to be defined in one or two lines.
Inline functions continue……..
E.g. inline double cube( double a)
{ return (a*a*a);} The inline keyword merely sends a
request, not a command, to the compiler.
The compiler may ignore the request if the function definition is too long or too complicated.
Inline functions continue……..
Situations where inline functions does not work
For functions returning values , if a loop, a switch, or a goto exists.
For functions not returning values, if a return statement exists.
If functions contain static variables.
If inline functions are recursive.
Inline functions continue……..E.g. #include(iostream.h>Using namespace std;Inline float mul(float x, float
y){Return(x*y);}Inline double div(double p,
double q){Return(p/q);}
Int main(){Float a=12.345;Float b=9.82;Cout<<mul(a,b)<<“
\n”;Cout<<div(a,b)<<“\
n”;Return 0;}
References
Reference variablesA reference variable provides an
alias (alternative name) for a previously defined variable.
A reference variable is created as follows:
data-type & ref-name = var-name;
Reference variables continue……
For e.g. , if we make the variable sum a reference to the variable total, then sum and total can be used interchangeably to represent that variable.float total = 100;float & sum = total;
sum is the alternative name declared to represent the variable total.
Reference variables continue……
Both variables refer to the same data object in the memory.
The statementtotal = total + 10;
will change the value of both total and sum to 110.
A reference variable must be initialized at the time of declaration.
Reference variables continue……
C++ assigns an additional meaning to &. Here & is not an address operator.
int n[10];int & x = n[10]; // x is an alias of n[10]char & a = ‘ \n ’; // initialize reference to a literal
Reference variables continue……
The following references are also allowed:
1. int x; int *p = &x;int & m = *p;
2. int & n = 50;
m refers to x which is pointed to by the pointer
p
creates an int object with value 50 and name n
References as function arguments A major application of reference variables is
in passing arguments to functions.void f(int & x) // uses reference{
x = x + 10; // x is incremented; so also m}void main(){
int m = 10;f(m); // function call………………
}
References as function argumentsWhen f(m) is executed, the following initialization occurs.
int & x = m;Thus x becomes an alias for m after executing f(m).Such function calls are called call by reference.In C we accomplish this using pointers and dereferencing technique.
References as function argumentsEg.#include<iostream.h
>using namespace std;void swap(int &x, &y){
int temp=x;x=y;y=temp;
}
Int main(){
int i,j;cin>>i>>j;cout<<i<<j<<endl;swap(i,j);cout<<i<<j;return 0;
}
A function can also return a reference.
int & max(int &x, int &y){
if(x>y)return x;
elsereturn y;
}
A function can also return a reference.
The function returns a reference to x or y and not the values.
This means the function call max(a,b) can appear on the left-
hand side of an assignmentmax(a, b) = -1;
is legal and assigns -1 to a if it is larger, otherwise -1 to b.
A function can also return a reference.
#include<iostream.h>#include<conio.h>void main(){
clrscr();int a=2, b=7;max(a,b)=-1;if(a==-1)
cout<<“max is a”;else
cout<<“max is b”;getch();
}
References and Pointers-similarities.
Pointers and references are essentially variables that hold memory addresses as their values.
A reference and a pointer are almost the same since they point only to one object.
Both a reference and a pointer need to be initialized during definition.
References and Pointers-differences.
A reference cannot refer to a NULL object, while a pointer can refer to a NULL object.
There is no need to test the validity of a reference before using it. But pointers be tested against NULL.
A reference always refers to the object with which it is initialized. Pointers may be reassigned to refer to different objects.
References and Pointers-differences.
Binding an object to a reference happens at the time of definition. The binding behavior of a pointer changes, based on what the pointer is declared as.
You can’t take the address of a reference like you can with pointers.
There is no “reference arithmetic”. But “pointer arithmetic” is possible.
END
Recommended