Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Object Oriented Programming Development - Week 4 z By: Rob Manton University of Luton z z Room: D104.

Similar presentations


Presentation on theme: "1 Object Oriented Programming Development - Week 4 z By: Rob Manton University of Luton z z Room: D104."— Presentation transcript:

1 1 Object Oriented Programming Development - Week 4 z By: Rob Manton University of Luton z Email: Rob.Manton@luton.ac.uk z Room: D104

2 2 Module Outline zIntroduction zThe non object oriented basics zClasses zDesign Approaches zTesting z Inheritance z Aggregation z Polymorphism z Multifile Development

3 3 Today: zFunctions recap zClasses recap zObjects recap zObject Persistence and Visibility.

4 4 Functions (not OO) void doSomething(); int main() { doSomething(); return 0; } void doSomething() { printf("Hello World!\n"); }. Function declaration goes before main(). Function body goes afterwards or alternatively put these in a separate file and #include it.

5 5 Working with classes For small classes you can add the definition above main() and the implementation below, but it is more usual to place them in separate files..

6 6 Working with classes Definition file (.h) and implementation file (.cpp) are added to project automatically when you do Insert/New Class

7 7 The two steps of Object Oriented Programming zMaking Classes: Creating, extending or reusing abstract data types. zMaking Objects interact: Creating objects from abstract data types and defining their relationships.

8 Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; born1997

9 Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; The definition of a class: The class keyword, followed by the class name. private attributes. public methods. the ; at the end

10 Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; This class has an attribute of type int. Note that each C++ data type and also abstract data types can be used as attribute types.

11 Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; This class has two (public) methods. One to set the attribute value and the other to retrieve the attribute value.

12 Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year); int getYearOfBirth(); }; void Creature::setYearOfBirth { yearOfBirth = year; } int Creature::getYearOfBirth() { return yearOfBirth; } Note that unless the methods are very short, declaration and implementation is usually separated. The declaration goes into a header file (.h), the implementation in a.cpp file.

13 Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; This method is an example for a ‘modifier’ method. It modifies the attribute. The method changes the state of the object.

14 Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; This method is an example for a ‘selector’ method. It returns information about the attribute but does not change the state of the object.

15 15 Classes & Objects zWhat may be different for all objects in a class, and what remains the same? zAll the objects in a class may have different attribute values (state data), but their allowed behaviours are all the same. So a class is a blueprint for objects

16 16 Objects & Classes zA class is defined by: yA Unique Name yAttributes yMethods z An object is defined by: yIdentity yState yBehaviour

17 17 Instantiating Objects zAn object is instantiated just like any other data type: int x; char y; Creature z; Declaring z of type ‘creature’ means we have generated an object with the attributes and methods of the class.

18 18 Multiple Objects zOf course we can create many objects of the same class: Creature myDog; Creature theMilkman; Creature myBestFriend; Creates three objects.

19 19 Sending Messages / Calling Methods. zA message is send to an object by calling a method of this object. Use the. (dot) for calling a method of an object. int k; k = theMilkman.getYearOfBirth(); myDog.setYearOfBirth(1998); Messages are sent to my dog and the milkman.

20 20 Back to the Instantiation... zAn object is instantiated just like any other data type: int x; char y; Creature z; Here the “default constructor” of the Creature class is automatically called. If we don’t like this we can specify constructors explicitly!

21 The Creature class with a user defined default constructor. class Creature { private: int yearOfBirth; public: // … Creature() { yearOfBirth = 1970; cout << “Hello.”; } }; The syntax for a constructor is similar as for a method, but: It has the same name as the class. It has no return value.

22 The Creature with a parametrized constructor. class Creature { private: int yearOfBirth; public: // … Creature(int year) { yearOfBirth = year; } }; This constructor can be used as follows: Creature theMilkman(1953); instantiates a 49 years old milkman.

23 The Creature with a copy constructor. class Creature { private: int yearOfBirth; public: // … Creature(Creature & otherCreature) { yearOfBirth = otherCreature.getYearOfBirth(); } }; Example: Creature myDog(1995); Creature myCat(myDog); creates a cat of the same age as the dog.

24 24 Constructors - summary zA constructor is always called when an object is created. zWe can define our own constructors (Note: a class can have more than one constructor). zIf an object is copied from another object then the copy constructor is called.

25 25 Classes exercise zOn paper for a change….

26 26 Again: Objects & Classes zA class is defined by: yA Unique Name yAttributes yMethods z An object is defined by: yIdentity yState yBehaviour

27 27 Again: Objects & Classes zA class is defined by: yA Unique Name yAttributes yMethods z An object is defined by: yIdentity yState yBehaviour But: We can give a class state and behaviour with the keyword static!

28 Example: The Creature class class Creature { private: int yearOfBirth; static int numberOfAllCreatures = 0; public: Creature() { // Constructor - counts the creatures. numberOfAllCreatures++; } static int getNumberOfAllCreatures() { return numberOfAllCreatures; } }; Note that all objects share the same value of the “class attribute” numberOfAllCreatures.

29 29 Last Week’s Summary. zA class is a blueprint for an object. zObjects are created similar to other data types (int, char, …). zThe construction of an object can be defined by the user. zMessages are sent to an object by calling a method. zstatic messes the concept of classes and objects (but is nevertheless useful).

30 30 This week:types of object zFour types of object (or any other data type) yAutomatic (local) objects yExternal (global) objects yStatic objects yDynamic objects

31 31 Types of object zFour types of object (or any other data type) yAutomatic (local) objects yExternal (global) objects yStatic objects yDynamic objects First three are objects with specific names

32 32 Types of object zFour types of object (or any other data type) yAutomatic (local) objects yExternal (global) objects yStatic objects yDynamic objects When objects are predictable enough to be identified at compile time

33 33 Types of object zFour types of object (or any other data type) yAutomatic (local) objects yExternal (global) objects yStatic objects yDynamic objects No fixed unique name Identified by the memory address which they occupy

34 34 Types of object zFour types of object (or any other data type) yAutomatic (local) objects yExternal (global) objects yStatic objects yDynamic objects For objects that can’t be defined at compile time: their number or identity may vary at run time

35 35 Automatic objects zInstantiated within the scope of a part of the program (between curly brackets somewhere) zAutomatically destroyed when object falls out of scope zvisible only within that scope (between when object declared and closing } )

36 36 External (global) objects zPersistent zVisible throughout program module zInstantiated outside any scope (curly brackets in C++) - usually at the top of your.cpp file zautomatically destroyed when program finishes zcan be referenced from other modules via extern keyword

37 37 Static objects zAs mentioned last week zPersistent for whole program - the same lifetime as an external (global) object - useful to ‘remember’ state zscope as for automatic object zuses keyword static

38 38 Dynamic objects zUseful where we can’t predict object identities, number or lifetimes. zCreated using the new keyword (you get a pointer to the object) zDestroyed using the delete keyword zNot destroyed automatically: You have to do it yourself!!

39 39 The lifetime of named objects (the first three) zAutomatic (local) objects exist while they are in scope zExternal (global) objects have file scope and exist for the whole program zStatic objects - may be instantiated in local scope with local visibility but persist from their declaration to the end of the program

40 40 class header file creature.h class creature { private: int yearOfBirth; public: creature(); virtual ~creature(); void setYearOfBirth(int year); int getYearOfBirth(); }; Private member variable (for encapsulation..) Public constructor with no parameters Accessor function (‘get’ something) Modifier function (‘set’ something)

41 41 class implementation file creature.cpp creature::creature() { cout << "constructor called for creature class." << endl; } creature::~creature() { cout << "destructor called for creature class." << endl; } int creature::getYearOfBirth() { return yearOfBirth; } void creature::setYearOfBirth(int year) { yearOfBirth = year; } Text message added to constructor and destructor to demonstrate when objects are created and destroyed

42 42 Automatic objects int main() { cout << "beginning of main function." << endl; creature myDog; cout << "end of main function." << endl; return 0; }

43 43 Automatic objects With automatic object, object destroyed automatically when it goes out of scope (destructor gets called)

44 44 Automatic objects int main() { cout << "beginning of main function." << endl; { creature myDog; } cout << "end of main function." << endl; return 0; cin; } Automatic object now within local scope defined by the curly brackets

45 45 Automatic objects Because it is declared in local scope the automatic object is now automatically destroyed when it goes out of scope, which is before the end of the main function

46 46 Automatic objects { creature myDog; myDog.setYearOfBirth(1966); }

47 47 Automatic objects { creature myDog; myDog.setYearOfBirth(1966); } This is legal. myDog is still in scope.

48 48 Automatic objects { creature myDog; } myDog.setYearOfBirth(1966);

49 49 Automatic objects { creature myDog; } myDog.setYearOfBirth(1966); This is not legal because myDog has gone out of scope (and been automatically destroyed) when the call to setYearOfBirth() is made.

50 50 External (global) objects creature myDog; int main() { cout << "beginning of main function." << endl; myDog.setYearOfBirth(1966); cout << "end of main function." << endl; return 0; } Object declared outside of any function or scope. This is legal because object is visible throughout entire program

51 51 External (global) objects With external (global) object, object is automatically destroyed when program ends

52 52 External (global) objects creature myDog; myDog.setYearOfBirth(1966); int main() { cout << "beginning of main function." << endl; cout << "end of main function." << endl; return 0; } Not legal: can only call methods and functions from within the braces of a function body

53 53 External (global) objects When is it useful to have a global object or variable? zTo make the object or variable visible in other source files within the same project zonly externally declared objects can be referenced in other program modules (other.cpp files) zknown as external linkage zuse extern keyword

54 54 External (global) objects extern creature myDog; void person::checkDog() { int dob=myDog.getYearOfBirth(); cout << "the dog was born in" << dob; } Say we have another class called person declared in person.h and implemented in person.cpp To refer to the myDog declared in the main file, we repeat the declaration creature myDog, but adding the extern keyword This calls the same creature object declared in the other program file

55 55 Static objects object::object() { value=0; } void object::addValue(int value_in) { value+=value_in; } int object::getValue() { return value; } This is part of the implementation file for a new class called object which we use to demonstrate the difference between auto and static objects...

56 56 Static objects for (i=0;i<5;i++) {cout << "now on iteration number " << i <<endl; object auto_object; auto_object.addValue(1); static object static_object; static_object.addValue(1); cout << "auto object contains " << auto_object.getValue() << endl; cout << "static object contains " << static_object.getValue() << endl; } We compare two different types of object - the auto version and the static one. Both are created from the same class, the only difference is the use of the keyword static

57 57 Static objects Auto object gets destroyed when it goes out of scope at end of each loop. Static object persists and doesn’t get destroyed when it goes out of scope

58 58 Static objects Auto object gets destroyed when it goes out of scope at end of each loop. Static object persists and doesn’t get destroyed when it goes out of scope

59 59 Dynamic objects zCreate a pointer to the object type - good practice to initialize them to NULL zthen use the new operator to return a pointer to the newly created object zobject * myObjectPtr=NULL; zmyObjectPtr = new object( );

60 60 Dynamic objects int main() { cout << "beginning of main function." << endl; creature * pDog=NULL; pDog = new creature(); cout << "end of main function." << endl; return 0; cin; } pDog is declared as a pointer to a creature object using creature * type.

61 61 Dynamic objects Note that there is no message from the destructor - the dynamic object is not automatically destroyed

62 62 Dynamic objects Note that there is no message from the destructor - the dynamic object is not automatically destroyed This is your job! You need to manually destroy the object using the delete command otherwise you will get a memory leak!

63 63 Dynamic objects int main() { cout << "beginning of main function." << endl; creature * pDog=NULL; pDog = new creature(); delete pDog; Manually destroy dynamic object when you have finished it using the delete command

64 64 Dynamic objects Now we are destroying the dynamically generated object manually - very important!!

65 65 Dynamic objects zHow do you access the methods of a dynamic object? zUse the -> operator instead of the dot (.) syntax zpDog->setYearOfBirth(1966);

66 66 Summary Automatic (local) objects zdestroyed automatically when go out of scope zvisible only within scope {} External (global) objects zdestroyed automatically at end of program zvisible throughout module zvisible throughout other modules in program using extern keyword

67 67 Summary static objects zvisible only within scope {} zpersist throughout program Dynamic objects zget a pointer to the object znot automatically destroyed zyour job to delete them otherwise you get a memory leak

68 68 Summary #define NUMDOGS 5 int main() {creature * myDogs[NUMDOGS]; int i; for (i=0;i<NUMDOGS;i++) { myDogs[i]=NULL; myDogs[i]=new creature(); myDogs[i]->setYearOfBirth(1970+i); } for (i=0;i<NUMDOGS;i++) { cout getYearOfBirth() << endl; } for (i=0;i<NUMDOGS;i++) { delete myDogs[i]; } return 0; }

69 69 Summary

70 70 Summary Automatic/external/static objects zHave a unique name zUseful when objects are predictable enough to be identified at compile time Dynamic objects zNo fixed unique name zIdentified by the memory address which they occupy zFor objects that can’t be defined at compile time: their number or identity may vary at run time


Download ppt "1 Object Oriented Programming Development - Week 4 z By: Rob Manton University of Luton z z Room: D104."

Similar presentations


Ads by Google