#OOP_D_ITS - 4th - C++ Oop And Class Structure


Published on

Published in: Health & Medicine, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

#OOP_D_ITS - 4th - C++ Oop And Class Structure

  1. 1. C++ OOP :: Class Structure<br />29/09/2009<br />1<br />Hadziq Fabroyir - Informatics ITS<br />
  2. 2. C++ Structures: Classes<br />In C++, the concept of structure has been generalized in an object-oriented sense:<br />classes are types representing groups of similar instances<br />each instance has certain fields that define it (instance variables)<br />instances also have functions that can be applied to them (represented as function fields) -- called methods<br />the programmer can limit access to parts of the class (to only those functions that need to know about the internals)<br />29/09/2009<br />2<br />Hadziq Fabroyir - Informatics ITS<br />
  3. 3. A Motivating Example<br />You declare a simple structure:<br />struct Robot {<br /> float locX;<br /> float locY;<br /> float facing;<br />};<br />Robot r1;<br />What if you never want locX or locY to be negative ?<br />Someone unaware of your restriction could set:<br />r1.locX = -5;<br />and you have a problem !<br />29/09/2009<br />3<br />Hadziq Fabroyir - Informatics ITS<br />
  4. 4. General Class Definition in C++<br />class ClassName {<br />access_modifier1:<br />field11_definition;<br />field12_definition;<br /> …<br />access_modifer2:<br />field21_definition;<br />field22_definition;<br /> …<br />};<br />ClassName is a new type (just as if declared as struct with typedef in C)<br />Possible access modifiers: <br />public<br />private<br />Protected<br />Fields can be variables (as in C structures) or functions<br />29/09/2009<br />4<br />Hadziq Fabroyir - Informatics ITS<br />
  5. 5. A Simple Class<br />class Robot {<br /> public:<br /> float getX() { return locX; }<br /> float getY() { return locY; }<br /> float getFacing() { return facing; }<br /> void setFacing(float f) { facing = f; }<br /> void setLocation(float x, float y);<br />private:<br /> float locX;<br /> float locY;<br /> float facing;<br />};<br />29/09/2009<br />5<br />Hadziq Fabroyir - Informatics ITS<br />
  6. 6. private Access Modifier<br />Fields marked as private can only be accessed by functions that are part of that class<br />In the Robot class, locX, locY, and facing are private float fields, these fields can only be accessed by functions that are in class Robot (getX, getY, getFacing, setFacing, setLocation)<br />Example:<br />void useRobot() {<br /> Robot r1;<br /> r1.locX = -5; // Error<br />29/09/2009<br />6<br />Hadziq Fabroyir - Informatics ITS<br />
  7. 7. publicAccess Modifier<br />Fields marked as public can be accessed by anyone<br />In the Robot class, the methods getX, getY, etc. are public<br />these functions can be called by anyone<br />Example:<br />void useRobot() {<br /> Robot r1;<br /> r1.setLocation(-5,-5); // Legal to call<br />29/09/2009<br />7<br />Hadziq Fabroyir - Informatics ITS<br />
  8. 8. structVS class<br />In C++ struct and class can be used interchangeably to create a class with one exception<br />What if we forget to put an access modifier before the first field?<br />struct Robot { OR class Robot {<br /> float locX; float locX;<br />In a class, until an access modifer is supplied, the fields are assumed to beprivate<br />In a struct, the fields are assumed to bepublic<br />29/09/2009<br />8<br />Hadziq Fabroyir - Informatics ITS<br />
  9. 9. What about protected?<br />C++ allows users to create classes based on other classes:<br />a FordCar class based on a general Car class<br />idea: the general Car class has fields (variables and functions that describe all cars)<br />the FordCar class then uses the fields from the general Car class and adds fields specific to FordCars<br />done with inheritance<br />public fields are inherited (as public)<br />private fields are not inherited<br />protected fields are like private, but can be inherited<br />29/09/2009<br />9<br />Hadziq Fabroyir - Informatics ITS<br />
  10. 10. Class Methods<br />Functions associated with a class are declared in one of two ways:<br />ReturnType FuncName(params) { code }<br />function is both declared and defined (code provided)<br />ReturnType FuncName(params);<br />function is merely declared, we must still define the body of the function separately<br />To call a method we use the . form:<br />classinstance.FuncName(args);<br />FuncName is a field just like any other field in the structured variable classinstance<br />29/09/2009<br />10<br />Hadziq Fabroyir - Informatics ITS<br />
  11. 11. Defined Methods<br />class Robot {<br /> public:<br />float getX() { return locX; }<br />};<br />Robot r1;<br />The function getX is defined as part of class Robot<br />To call this method:<br />cout &lt;&lt; r1.getX() &lt;&lt; endl; // prints r1’s locX<br />29/09/2009<br />11<br />Hadziq Fabroyir - Informatics ITS<br />
  12. 12. Defining Methods Separately<br />For methods that are declared but not defined in the class we need to provide a separate definition<br />To define the method, you define it as any other function, except that the name of the function is ClassName::FuncName<br />:: is the scope resolution operator, it allows us to refer to parts of a class or structure<br />29/09/2009<br />12<br />Hadziq Fabroyir - Informatics ITS<br />
  13. 13. A Simple Class<br />class Robot {<br /> public:<br /> void setLocation(float x, float y);<br /> private:<br /> float locX;<br /> float locY;<br /> float facing;<br />};<br />void Robot::setLocation(float x, float y) {<br /> if ((x &lt; 0.0) || (y &lt; 0.0))<br /> cout &lt;&lt; “Illegal location!!” &lt;&lt; endl;<br /> else {<br /> locX = x;<br /> locY = y;<br /> }<br />}<br />29/09/2009<br />13<br />Hadziq Fabroyir - Informatics ITS<br />
  14. 14. Types of Class Methods <br />Generally we group class methods into three broad categories:<br />accessors - allow us to access the fields of a class instance (examples: getX, getY, getFacing), accessors do not change the fields of a class instance<br />mutators - allow us to change the fields of a class instance (examples: setLocation, setFacing), mutators do change the fields of a class instance<br />manager functions- specific functions (constructors, destructors) that deal with initializing and destroying class instances (more in a bit)<br />29/09/2009<br />14<br />Hadziq Fabroyir - Informatics ITS<br />
  15. 15. Accessors & Mutators<br />Why do we bother with accessors and mutators?<br />Why provide getX()?? Why not just make the locX field publicly available?<br />By restricting access using accessors and mutators we make it possible to change the underlying details regarding a class without changing how people who use that class interact with the class<br />Example: what if I changed the robot representation so that we no longer store locX and locY, instead we use polar coordinates (distance and angle to location)?<br />If locX is a publicly available field that people have been accessing it, removing it will affect their code<br />If users interact using only accessors and mutators then we can change things without affecting their code<br />29/09/2009<br />15<br />Hadziq Fabroyir - Informatics ITS<br />
  16. 16. Rewritten Robot Class<br />class Robot {<br /> public:<br /> float getX() { return dist * cos(ang); }<br /> float getY() { return dist * sin(ang); }<br /> void setLocation(float x, float y);<br /> private:<br />float dist;<br /> float ang;<br />};<br />void Robot::setLocation(float x, float y) {<br /> if ((x &lt; 0.0) || (y &lt; 0.0))<br /> cout &lt;&lt; “Illegal location!!” &lt;&lt; endl;<br /> else {<br />dist = sqrt(x * x + y * y);<br /> ang = atan2(y,x);<br /> }<br />}<br />29/09/2009<br />16<br />Hadziq Fabroyir - Informatics ITS<br />
  17. 17. Object-Oriented Idea<br />Declare implementation-specific fields of class to be private<br />Provide public accessor and mutator methods that allow other users to connect to the fields of the class<br />often provide an accessor and mutator for each instance variable that lets you get the current value of that variable and set the current value of that variable<br />to change implementation, make sure accessors and mutators still provide users what they expect<br />29/09/2009<br />17<br />Hadziq Fabroyir - Informatics ITS<br />
  18. 18. Static Instance Variables<br />C++ classes may also contain, static instance fields -- a single field shared by all members of a class<br />Often used when declaring class constants (since you generally only need one copy of a constant)<br />To make a field static, add the static keyword in front of the field<br />can refer to the field like any other field (but remember, everybody shares one copy)<br />static variables are also considered to be global, you can refer to them without an instance<br />static fields can be initialized (unlike other fields)<br />29/09/2009<br />18<br />Hadziq Fabroyir - Informatics ITS<br />
  19. 19. Static Fields Example<br />class Robot {<br /> public:<br />static int numRobots = 0;<br /> static const float minX = 0.0;<br /> static const float maxX = 100.0;<br /> void initializeRobot() {<br />numRobots++;<br /> }<br /> void setLocation(float x, float y);<br />}<br />void Robot::setLocation(float x, float y) {<br /> if ((x &lt; minX) || (x &gt; maxX))<br /> …<br />}<br />29/09/2009<br />19<br />Hadziq Fabroyir - Informatics ITS<br />
  20. 20. Static Fields as Global Variables<br />One can examine public static fields of a class outside of that class using the form:<br />ClassName::StaticFieldName<br />Example:<br />void main() {<br /> Robot r1, r2;<br /> r1.initializeRobot();<br /> r2.initializeRobot();<br /> cout &lt;&lt; Robot::numRobots &lt;&lt; “ robots. ”;<br />29/09/2009<br />20<br />Hadziq Fabroyir - Informatics ITS<br />
  21. 21. The Need for Manager Functions<br />To make the previous program work we have to explicitly call the routine initializeRobot, wouldn’t it be nice to have a routine that is automatically used to initialize an instance -- C++ does<br />C++ provides for the definition of manager functions to deal with certain situations:<br />constructors (ctor) - used to set up new instances<br />default - called for a basic instance<br />copy - called when a copy of an instance is made (assignment)<br />other - for other construction situations<br />destructors (dtor) - used when an instance is removed<br />29/09/2009<br />21<br />Hadziq Fabroyir - Informatics ITS<br />
  22. 22. When Managers Called<br />void main() {<br /> Robot r1; // default ctor (on r1) <br /> Robot r2; // default ctor (on r2)<br /> Robot* r3ptr;<br /> r3ptr = new Robot; // default ctor on<br /> // Robot object r3ptr points to<br /> r2 = r1; // copy ctor<br /> delete r3ptr; // dtor<br />} // dtor (on r1 and r2) when main ends<br />29/09/2009<br />22<br />Hadziq Fabroyir - Informatics ITS<br />
  23. 23. The Default Constructor (ctor)<br />A default constructor has no arguments, it is called when a new instance is created<br />C++ provides a default ctor that initializes all fields to 0<br />To write your own, add following to your class:<br />class MyClass {<br /> public:<br /> …<br />MyClass() { // repeat class name, no<br />code here // return type<br /> }<br />}<br />29/09/2009<br />23<br />Hadziq Fabroyir - Informatics ITS<br />
  24. 24. Example Default ctor<br />class Robot {<br /> public:<br /> static int numRobots = 0;<br />Robot() {<br /> numRobots++;<br /> locX = 0.0;<br /> locY = 0.0;<br /> facing = 3.1415 / 2;<br /> }<br /> private:<br /> float locX;<br /> float locY;<br /> float facing;<br />}<br />29/09/2009<br />24<br />Hadziq Fabroyir - Informatics ITS<br />
  25. 25. Destructor (dtor)<br />A destructor is normally not critical, but if your class allocates space on the heap, it is useful to deallocate that space before the object is destroyed<br />C++ provides a default dtor that does nothing<br />can only have one dtor<br />To write your own, add following to your class:<br />class MyClass {<br /> public:<br /> …<br />~MyClass() { <br />code here<br /> }<br />}<br />29/09/2009<br />25<br />Hadziq Fabroyir - Informatics ITS<br />
  26. 26. Example dtor<br />class Robot {<br /> public:<br /> char *robotName;<br />Robot() {<br /> robotName = 0;<br /> }<br /> void setRobotName(char *name) {<br /> robotName = new char[strlen(name)+1];<br /> strcpy(robotName,name);<br /> }<br />~Robot() {<br /> delete [] robotName;<br /> }<br />}<br />29/09/2009<br />26<br />Hadziq Fabroyir - Informatics ITS<br />
  27. 27. The Copy ctor<br />A copy constructor is used when we need a special method for making a copy of an instance<br />example, if one instance has a pointer to heap-allocated space, important to allocate its own copy (otherwise, both point to the same thing)<br />To write your own, add following to your class:<br />class MyClass {<br /> public:<br /> …<br />MyClass(const MyClass& obj) {<br />code here<br /> }<br />}<br />29/09/2009<br />27<br />Hadziq Fabroyir - Informatics ITS<br />
  28. 28. Example Copy ctor<br />class Robot {<br /> public:<br /> char *robotName;<br /> void setRobotName(char *name) {<br /> robotName = new char[strlen(name)+1];<br /> strcpy(robotName,name);<br /> }<br />Robot(const Robot& obj) {<br /> robotName = new char[strlen(obj.robotName)+1];<br /> strcpy(robotName,obj.robotName);<br /> }<br />}<br />29/09/2009<br />28<br />Hadziq Fabroyir - Informatics ITS<br />
  29. 29. Other ctors<br />It is often useful to provide constructors that allow the user to provide arguments in order to initialize arguments<br />Form is similar to the copy ctor, except parameters are chosen by programmer:<br />class MyClass {<br /> public;<br /> …<br />MyClass(parameters) {<br />code here<br /> }<br />}<br />29/09/2009<br />29<br />Hadziq Fabroyir - Informatics ITS<br />
  30. 30. Example ctor<br />class Robot {<br /> public:<br /> Robot(float x, float y, float face) {<br /> locX = x;<br /> locY = y;<br /> facing = face;<br /> }<br />}<br />calling:<br /> Robot r1(5.0,5.0,1.5);<br /> Robot r2(5.0,10.0,0.0);<br /> Robot* rptr;<br /> rptr = new Robot(10.0,5.0,-1.5);<br />29/09/2009<br />30<br />Hadziq Fabroyir - Informatics ITS<br />
  31. 31. A Combination ctor<br />Can combine a ctor that requires arguments with the default ctor using default values:<br />class Robot {<br /> public:<br />Robot(float x = 0.0, float y = 0.0, <br /> float face = 1.57075) {<br /> locX = x; locY = y; facing = face;<br /> }<br />}<br />calling:<br /> Robot r1; // ctor called with default args<br /> Robot r2(); // ctor called with default args<br /> Robot r3(5.0); // ctor called with x = 5.0<br />Robot r4(5.0,5.0); // ctor called with x,y = 5.0<br /> … <br />29/09/2009<br />31<br />Hadziq Fabroyir - Informatics ITS<br />
  32. 32. Hiding the Default ctor<br />Sometimes we want to make sure that the user gives initial values for some fields, and we don’t want them to use the default ctor<br />To accomplish this we declare an appropriate ctor to be used in creating instances of the class in the public area, then we put the default ctor in the private area (where it cannot be called)<br />29/09/2009<br />32<br />Hadziq Fabroyir - Informatics ITS<br />
  33. 33. Example ctor<br />class Robot {<br /> public:<br />Robot(float x, float y, float face) {<br /> locX = x;<br /> locY = y;<br /> facing = face;<br /> }<br /> private:<br /> Robot() {}<br />}<br />calling:<br /> Robot r1(5.0,5.0,1.5);<br /> Robot r2; // ERROR, attempts to call default ctor<br />29/09/2009<br />33<br />Hadziq Fabroyir - Informatics ITS<br />
  34. 34. For your practice …<br />Exercise 9.5 <br />Complex Class<br />Properties: float realPart, float imaginaryPart <br />Method (Mutators): Complex addBy(Complex), ComplexSubstractBy(Complex)<br />Lab Session for upper order (Senin, 15.00-17.00)<br />Lab Session for lower order (Senin, 19.00-21.00)<br />Please provide:<br /> the softcopy(send it by email – deadline Sunday 23:59)<br />the hardcopy(bring it when attending the lab session)<br />29/09/2009<br />Hadziq Fabroyir - Informatics ITS<br />34<br />
  35. 35. ☺~ Next: C++ OOP :: Overloading ~☺<br />[ 35 ]<br />Hadziq Fabroyir - Informatics ITS<br />29/09/2009<br />