object-oriented programming with c++ - iupjchrispe/mthsc_330/notes/oopv1.pdf · object-oriented...
TRANSCRIPT
Object-Oriented Programming with C++ Prepared by Marko Puljic
Why Use Objects:software objects, examples
Class Design:declaring objects, constructors, overloading, cohesion
Inheritance:examples, multiple inheritance, coupling
Polymorphismwhy, abstract base class, example
Criticism
Other Programming Paradigms
object <- software bundle of related state and behavior real-world objects:
e.g dog state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail)
humans like objects
object stores its state in data and exposes its behavior through functions
interaction through an object's functions: data encapsulation
objects can contain other objects
Benefits:
– Modularity; object maintained independently of the other objects.
– Information-hiding; through methods, the details remain hidden.
– Code re-use; re-use of object in the new program.
– Debugging ease; easier to spot problematic parts of program.
Why Use Object: Software
Why use Objects: Example
Simple Neuron Object
state:Number of synapses (in).Number of neurons it reaches (out).Neuron's electric potential.
behavior:Being excited (how much).Excites the neighbors.
Stock Object
state:Name of stock.Number of stocks owned.Value of stock.
behavior:Acquire stocks.Sell stocks.
Why use Objects: State & Behavior of Polygons?
class is an expanded concept of a data structure: it can hold both data and functions.
object is an instantiation of a class (another definition).In terms of variables, a class would be the type, and an object would be the variable.
example:
class Rectangle{private:
int x, y; public: void setValues( int, int ); int area(){ return ( x * y ); }
};
void Rectangle::setValues( int a, int b ){ x = a; y = b;
}
Class Design
//example: one class, two objects; RectangleEG2.cpp#include <iostream>//header file; part of the C++ standard library using namespace std;//so we have defined names for shorter writings
class Rectangle{ private: int x, y; public: void setValues( int a, int b ){ x = a; y = b; } int area(){ return( x * y ); }};
int main(){
Rectangle rect, rectb;rect.setValues( 3, 4 );rectb.setValues( 5, 6 );cout << "rect area: " << rect.area() << endl;//cout and endl comes from namespacecout << "rectb area: " << rectb.area() << endl;return 0;
}
Class Design: Declaring Several Objects
Class Design: Constructors//example: constructor is automatically called with a new object; RectangleEG3.cpp#include <iostream>using namespace std;
class Rectangle{ private:
int width, height; public:
Rectangle( int a, int b ){width = a; height = b;
}int area(){ return (width * height ); }
};
int main(){
Rectangle rect( 3, 4 );Rectangle rectb( 5, 6 );cout << "rect area: " << rect.area() << endl;cout << "rectb area: " << rectb.area() << endl;return 0;
}
Class Design: Overloading Constructors//overloading constructors and functions; RectangleEG5.cpp#include <iostream>using namespace std;
class Rectangle{ private: int width, height; public: Rectangle(){ width = 5; height = 5; } Rectangle( int a, int b ){ width = a; height = b; } int area( void ){ return ( width * height ); }
int area( int a, int b ){ return ( a * b ); }};int main(){ Rectangle rect( 3, 4 ); Rectangle rectb; cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl;
cout << "area of 5 x 5: " << rectb.area( 5, 5 ) << endl; return 0;}
Lack of Cohesion in Methods (LCOM Metric)
LCOM1:For each pair of functions (M) find set of data (A) they access. If they have disjointed sets of data accesses, P increases.If they share at least one field access, Q increases by one.
After considering each pair of methods:R = (P > Q) ? (P - Q) : 0
Low R; high coupling between methods <- indicates reusability, good design. Chidamber and Kemerer provided the definition of this metric in 1993.
Class Design: Cohesion
R = 8 high coupling
Inheritance Between Classes
any state and behavior that is inherited from another class
Inheritance allows to create classes which are derived from other classes
classes automatically include some of its "parent's" members, (plus its own)
class Polygon{ protected: int width, height; public: Polygon(){}//empty constructor void setValues( int a, int b ){ width = a; height = b; }};class Rectangle: public Polygon { public: int area (){ return( width * height ); }};class Triangle: public Polygon { public: Triangle( string n ){ cout << "triangle name is " << n << endl; } int area(){ return ( width * height / 2 ); }}; //derived classes; RectangleEG12.cpp
#include <iostream>using namespace std;#include "poly.h"
int main () { Rectangle rect; Triangle trgl( "triangle" ); rect.setValues( 4 ,5 ); trgl.setValues( 4, 5 ); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;}
Inheritance Between Classes: Example
Inheritance Between Classes: Multiple Inheritanceclass Polygon{ protected: int width, height; public: void setValues( int a, int b ){ width = a; height = b; }};class Output{ public: void output( int i ){ cout << i << endl; }};class Rectangle: public Polygon, public Output{ public: int area(){ return ( width * height ); }};class Triangle: public Polygon, public Output{ public: int area(){ return ( width * height / 2 ); }};int main(){//RectangleEG14.cpp Rectangle rect; Triangle trgl; rect.setValues( 4, 5 ); trgl.setValues( 4, 5 ); rect.output( rect.area() ); trgl.output( trgl.area() ); return 0;}
low couplinglower coupling <- more flexible, extensible softwareLow coupling often correlates with high cohesion, and vice versa
high coupling
Inheritance: Coupling
//actual type of the object determines the method to be calledclass Polygon{ protected: int width, height; public: void setValues( int a, int b ){ width = a; height = b; } virtual int area() = 0;//to be changed in each class inherits this method};class Rectangle: public Polygon{ public: int area(){ return ( width * height ); }};class Triangle: public Polygon{ public: int area(){ return ( width * height / 2 ); }};
int main(){//RectangleEG17.cpp Rectangle rect; Triangle trgl; Polygon * ppoly1 = ▭ Polygon * ppoly2 = &trgl; ppoly1->setValues( 4, 5 ); ppoly2->setValues( 4 ,5 ); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; return 0;}
Polymorphism: Abstract Base Classes
//dynamic allocation and polymorphism; RectangleEG19.cppclass Polygon{ protected: int width, height; public: void setValues( int a, int b ){ width = a; height = b; } virtual int area(){}; void printarea(){ cout << area() << endl; }};
class Rectangle: public Polygon{ public: int area(){ return ( width * height ); }};
class Triangle: public Polygon{ public: int area(){ return ( width * height / 2 ); }};
#include <iostream>using namespace std;#include "poly4.h"
int main(){ Polygon * ppoly1 = new Rectangle; Polygon * ppoly2 = new Triangle; ppoly1->setValues( 4 ,5 ); ppoly2->setValues( 4, 5 ); ppoly1->printarea(); ppoly2->printarea(); delete ppoly1; delete ppoly2; return 0;}
Polymorphism: Abstract Base Classes; Example
Inheritance, Simula (1960s Oslo); Ole-Johan Dahl, Kristen Nygaard
reuse an existing class with modificationsan extension to an existing class; adding functionalityJohan and Kristen got Turing Award
(pics from www.cse.psu.edu and www.ub.uio.no)
Encapsulation is concerned with:how to manipulate data through the state and the behaviors
state to be accessed and modified only through behaviors; better controlhiding the details of how the object works.
only accessible part of the object to the outside world is its behaviorssee RectangleEG20.cpp
Overloading several methods with a same name but different parameter types
Overriddinginherited methods that are redefined -> same arguments
Polymorphismactual type of the object determines the method to be called
Summary
CriticismJoe Armstrong (www.sics.se/~joe)
(Erlang general-purpose concurrent programming language): “You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.”
Alexander Stepanov (www.stepanovpapers.com)
(designer and implementer of the C++ Standard Template Library):Suggested that OOP provides a mathematically-limited viewpoint: "almost as much of a hoax as Artificial Intelligence".
Paul Graham (www.paulgraham.com)
(Lisp and co-founding Viaweb, became the Yahoo! Store):“Object-oriented programming is popular in big companies... generates a lot of what looks like work...”
Programming ParadigmsImperative programming; emphasizes changes in state
describes computation in terms of statements that change a program state
Functional programming; emphasizes the application of functionscomputation as the evaluation of mathematical functions and avoids state and mutable data
Structured programming; sequence, selection, and repetitionsequencing, selection, and iteration are sufficient to express any computable function
Event-driven programmingthe flow of the program is determined by events
Object oriented programming;uses "objects" – data structures consisting of data fields and methods
Declarative programming; any style of programming that is not imperativeexpresses the logic of a computation without describing its control flow
Automata-based programming; the program or its part is thought of as a model of a finite state machine
In terms of total instruction path length:program in an imperative style, (without any subroutines) <- the lowest count. the binary size might be larger
functional programs reference more "non-local" physical instructions may increase cache misses and increase instruction fetch overhead processors
paradigms that use subroutines extensivelyuse a greater percentage of total resources on the subroutine linkages
object oriented programs - that deliberately do not alter program state directly - using mutator methods to encapsulate the state changes have a greater overhead
Programming Paradigms