The Object-Oriented Approach
Junaed Sattar September 24, 2008 Lecture 4
Today
object-based and object-oriented approach to software creation
Why OOP? OO basics, terminology Why OOP with C++?
Why do we need an OO approach?
Adaptation to change
non OO approach can be robust, structured but lacks flexibility maintainability (a.k.a. service packs) extensibility (newer releases of software) distributed design and development
Better handling software demands
C++ as an OO language?
Great choice, because:
has a large community of users multiparadigm (remember?) performance legacy code access and reuse
Large user base
thriving community of developers high quality compilers, development aids documentation, forums, organizations
Multiparadigm
Does not need to be OO
unlike Java
Non OO (i.e. procedural) approach can be used as deemed necessary
small subroutines, programs
Performance & Legacy Code
properly written C++ programs are memory and performance optimized
fast code, small memory footprint OO design leads to easy performance tuning makes it easy to port C code to C++
C++ is ~98% compatible with C
OO Fundamentals
Objects Classes Inheritance Polymorphism
Objects ... and classes?!
Aren't they the same thing? Classes are like blueprints; they are the specifications, not instantiations Objects are like houses built from blueprints. It really exists.
Classes
The packaging unit in OO programming localizes (i.e. packages) data and member functions
i.e. combines states and services on those states
Why do we need this?
Classes
Easier to apply changes
changes in abstraction/concept inevitable make changes to one place when needed
Logical association becomes functional, syntactual
imagine a software specification of a car service accelerate should only affect state speed
OO and N-OO
C:
floatspeed=0.0; //thisisaglobal ... voidAccelerate() { speed+=0.1; }
C++
classCar{ floatspeed; ... ... voidAccelerate() { speed+=0.1; } }
Objects
Qualities of an object?
not just a package for data and methods fundamental purpose is to provide services hence should be alive, responsible, intelligent
Alive?
Must do some useful thing
contrast with dead data in procedural languages dead data are declared but lie in memory, not used most of the time data must not be garbage i.e. uninitialized dynamic memory
Must maintain a coherent state
Responsible?
Others should be able to delegate tasks
objects are self contained inner workings are protected should perform task in a reliable, consistent manner
Intelligent?
Should know how to perform task
provides services to other users removes complexity from many to few
Intelligent?
Should know how to perform task
provides services to other users removes complexity from many to few o.e. why not airplane rentals?
First steps
Write down requirements
roles and responsibilities what services to provide? why does it exist? is it required?
simplifies design process, streamlines project
C++ class syntax
classClassName{ private: //memberdataandmethods (declarations/definitions) protected: //memberdataandmethods (declarations/definitions) public: //memberdataandmethods (declarations/definitions) };
Public elements
accessible from outside the class NOT accessible from outside the class we'll see soon.
Private elements
Protected?
Example Class: declaration
classVehicle{ private: intnPass; doublegasCapacity; boolHybrid; floatfSpeed; public: Vehicle();//Constructor ~Vehicle();//Destructor boolLoadPassengers(intnp); voidAccelerate(); boolisHybrid()const; floatGetSpeed()const; };
Synopsis
By default, class members are private
specifying private at the start of the declaration is optional can have many more, just an example for now two special ones
Has four data members (states)
Has six methods
More Synopsis
Constructors are called when object is created
always called during instantiation compiler provides default (invisible) dummy constructor provide our own when data initialization is required compiler provides default as well perform data clean up in here
Destructors are called when object is destroyed
Note
Providing our own constructor (and/or destructor) will disable the default constructor given by the compiler.
Even More Synopsis
What are those consts after the methods?
constant member functions, or methods cannot change member variables C++'s way of enforcing read-only access to member variables will generate compiler error if changes to class member variables are made in constant methods
Example Class: definition
Vehicle::Vehicle{ nPass=5; gasCapacity=100; Hybrid=true; fSpeed=0.0f; } boolVehicle::LoadPassengers(intnp) { if(nPass<=np)nPass=np; } voidVehicle::Accelerate(){ fSpeed+=5.0; } boolVehicle::isHybrid()const{returnHybrid;} floatVehicle::GetSpeed()const{returnfSpeed;}
An alternative declaration/definition
classVehicle{ private: intnPass; doublegasCapacity; boolHybrid; floatfSpeed; public: Vehicle(){ nPass=5; gasCapacity=100; Hybrid=true; fSpeed=0.0f; } ~Vehicle(){};//Destructor boolLoadPassengers(intnp) { if(nPass<=np)nPass=np; } ...
...Continued
voidAccelerate(){ fSpeed+=5.0; } boolisHybrid()const{returnHybrid;} floatGetSpeed()const{returnfSpeed;} };//classdeclarationends
Inline functions
Avoids the overhead of the function call
expanded by the preprocessor like a macro in C equivalent to a C define preprocessor statement also can use the inline keyword
Alternate syntax
classVehicle{ ... boolLoadPassengers(int np) { if(nPass<=np) nPass=np; } classVehicle{ ... boolLoadPassengers(int np); }; inlinebool Vehicle::LoadPassengers( intnp) { if(nPass<=np) nPass=np; }
Inline functions
Use inline for short, frequently-used methods Functions that contain static data, loops, switch statements, or recursive calls cannot be inlined
Instantiation
Creating an object
intmain(){ Vehicleferrari; ferrari.Accelerate(); ... return0; }
Can only access public methods or data Privates are hidden (i.e. encapsulated)
Next class
More about access protection encapsulation object pointers and dynamic objects