Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Equal Opportunity University CS 215-401 Fall 2014 Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz Slide modified from Link 1 Link.

Similar presentations


Presentation on theme: "An Equal Opportunity University CS 215-401 Fall 2014 Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz Slide modified from Link 1 Link."— Presentation transcript:

1 An Equal Opportunity University CS 215-401 Fall 2014 Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz Slide modified from Link 1 Link 1

2 2 Programming Concept Evolution Unstructured Procedural Object-Oriented

3 3 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.

4 4 Object-Oriented Concept Objects of the program interact by sending messages to each other

5 5 Objects An object is an encapsulation of both functions and data Objects are an Abstraction –represent real world entities –Classes are data types that define shared common properties or attributes –Objects are instances of a class Objects have State –have a value at a particular time Objects have Operations –associated set of operations called methods that describe how to carry out operations Objects have Messages –request an object to carry out one of its operations by sending it a message –messages are the means by which we exchange data between objects

6 6 OO Perspective Let's look at the Rectangle through object oriented eyes: Define a new type Rectangle (a class) –Data width, length –Function area() Create an instance of the class (an object) Request the object for its area In C++, rather than writing a procedure, we define a class that encapsulates the knowledge necessary to answer the question - here, what is the area of the rectangle.

7 7 class Rectangle { private: int width, length; public: Rectangle(int w, int l) { width = w; length = l; } main() { Rectangle rect(3, 5); cout << rect.area()<<endl; } int area() { return width*length; } }; Example Object Oriented Code

8 8 Object-Oriented Programming Languages Characteristics of OOPL: –Encapsulation –Inheritance –Polymorphism –Overloading OOPLs support : –Modular Programming –Ease of Development –Maintainability

9 9 Characteristics of OOPL Encapsulation: C ombining data structure with actions –Data structure: represents the properties, the state, or characteristics of objects –Actions: permissible behaviors that are controlled through the member functions Data hiding: Process of making certain data inaccessible Inheritance: A bility to derive new objects from old ones –permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more general/base class –ability to define a hierarchical relationship between objects Polymorphism: A bility for different objects to interpret functions differently. Overloading

10 Class Definitions

11 2 Visibility Modifiers ● Permissions for data members and member functions: ● private :Can only be accessed by that class protected :Can be accessed by subclasses public :Can be accessed by anyone ● ● ● Class members are private by default Cannot be applied to the whole class: ● publicclassA;//Don'tdothis! protectedclassB;//Orthis!

12 Class Definitions 3 Example classBox { public: //Classname //Publicmembers section private: //Privatememberssection intweight; }; //Noticethesemicolon Box(intw){weight=w;} intgetWeight()const{returnweight;}

13 Example in UML ● Class Definitions 4 Always 3 sections – Name – Data members – Member functions Visibility modifiers – Public (+) – Private (-) – Protected (#) ● Box -weight : int +getWeight() : int

14 5 Inline Methods ● A method that is implemented inside the class definition is called an inline method. The compiler may choose to expand the body of the method at the point of call. ● ● The compiled code executes faster since it avoids the overhead of a function call. Inlining can make the compiled code larger and more complex (usually not desirable properties). ● ● Use inlining only for very short methods. Never use them with loops or recursive calls. ●

15 Class Definitions 6 Class Interface ● Usually the class definition is in an interface (or header) file, and the implementation in an implementation (or source) file. ● Interface files usually have a.h extension. Implementation files can have a.cpp,.c++, or.C. The filename does not have to match the class name. ● ● ● A #include statement is used to include the class definition into the implementation file: #include“myclass.h”

16 Class Definitions 7 Fully Qualified Names ● Use a #ifndef... #define... #endif in the header file to avoid including the class definition more than once. Methods implemented in the source file use a fully qualified function name. ● ● This avoids conflicts with other classes that have a method with the same name. A fully qualified name consists of the class name, a double colon, and the method name:...ClassName::methodName... ●

17 Class Definitions 8 Example ● box.h #ifndef #define BOX_H classBox { public: Box(intw); intgetWeight()const; private: intweight; }; #endif ● box.c #include“box.h” Box::Box(intw) { weight=w; } intBox::getWeight( { returnweight; } )const

18 Class Definitions 1212 Constructors ● Constructors serve two purposes:they create and initialize an object A constructor is a method with the same name as the class, and does not have a return type There are three types of constructors: ● ● ● A default constructor takes no arguments An ordinary constructor has some arguments A copy constructor is used to make copies (clone) ● ●

19 Class Definitions 1313 Copy Constructor ● A copy constructor is used to make a copy of an object value. ● It takes an instance of the same class as a constant reference argument: Box(constBox&b); A copy constructor is often called implicitly, such as when passing by value: ● doStuff( a);//Copyconstructorcalled. Boxa;//Defaultconstructorgets //calledimplicitly,too.

20 Class Definitions 1414 Example classBox{ public: Box() //Defaultconstructor {weight=0;}=0;} private: intweight; }; Box(intw)//Ordinaryconstructor {weight=w;} Box(constBox&b)//Copyconstructor {weight=b.weight;}

21 Class Definitions 2 Destructors ● The destructor is implicitly called when an object is deleted ● Object may have been explicitly deleted using delete An object could also be automatically deleted at the end of a function if the object is stack-resident The destructor is never called directly ● ● ● The destructor is defined using a tilde followed by the class name and takes no arguments: ~Box();

22 Class Definitions 2323 Destructors cont. ● The destructor usually deletes any heap-resident memory the object may have allocated: classStorage{ public: Storage(ints){space=newint[s];} int&operator[](inti) {returnspace[i];} ~Storage(){delete[]space;} private: int*space; };

23 Class Definitions 2424 The keyword this ● Every method has a pointer named this which points to the object the method was invoked on classBox{ public: Box(intw):weight(w){} Box&doStuff(){ this->weight= 73; return*this; } private: intweight; };

24 Class Definitions 2626 Friends ● A class can have friends that are allowed to access its private data members and functions: classBox{ public: Box(intw):weight(w){} //Allowaccessforglobalfunctionoperator<< friendostream&operator<<(ostream&out); //AllowclassCratetoaccessweight friendclassCrate; private: intweight; };

25 Friend Functions Example #include using namespace std; class Rectangle { int width, height; public: Rectangle() {} Rectangle (int x, int y) : width(x), height(y) {} int area() {return width * height;} friend Rectangle duplicate (const Rectangle&); }; Rectangle duplicate (const Rectangle& param) { Rectangle res; res.width = param.width*2; res.height = param.height*2; return res; } int main () { Rectangle foo; Rectangle bar (2,3); foo = duplicate (bar); cout << foo.area() << '\n'; return 0; } Source: http://www.cplusplus.com/doc/tutorial/inheritance/

26 Friend Class Example Source: http://www.cplusplus.com/doc/tutorial/inheritance/ #include using namespace std; class Square; class Rectangle { int width, height; public: int area () {return (width * height);} void convert (Square a); }; class Square { friend class Rectangle; private: int side; public: Square (int a) : side(a) {} }; void Rectangle::convert (Square a) { width = a.side; height = a.side; } int main () { Rectangle rect; Square sqr (4); rect.convert(sqr); cout << rect.area(); return 0; }

27 More About Friends In the previous example: Rectangle is considered a friend class by Square, but Square is not considered a friend by Rectangle. Therefore, the member functions of Rectangle can access the protected and private members of Square but not the other way around. Of course, Square could also be declared friend of Rectangle, if needed, granting such an access. Another property of friendships is that they are not transitive: The friend of a friend is not considered a friend unless explicitly specified.

28 28 Class Definition Data Members Can be of any type, built-in or user-defined non-static data member Each class object has its own copy static data member Acts as a global variable One copy per class type, e.g. counter

29 29 class Rectangle { private: int width; int length; static int count; public: void set(int w, int l); int area(); } Static Data Member Rectangle r1; Rectangle r2; Rectangle r3; width length width length width length r1 r3 r2 count

30 Static Data Member #include using namespace std; class Box{ public: static int objectCount; // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0){ cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume(){ return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void){ Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects. cout << "Total objects: " << Box::objectCount << endl; return 0; } Source: http://www.tutorialspoint.com/cplusplus/cpp_static_members.htm

31 Inheritance

32 32 class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept Rectangle Triangle Polygon class Polygon{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); };

33 33 Rectangle Triangle Polygon class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; class Rectangle : public Polygon{ public: float area(); }; class Rectangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept

34 34 Rectangle Triangle Polygon class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle : public Polygon{ public: float area(); }; class Triangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept

35 35 Inheritance Concept Point Circle3D-Point class Point{ protected: int x, y; public: void set (int a, int b); }; class Circle : public Point{ private: double r; }; class 3D-Point: public Point{ private: int z; }; xyxy xyrxyr xyzxyz

36 36 Augmenting the original class Specializing the original class Inheritance Concept RealNumber ComplexNumber ImaginaryNumber Rectangle Triangle Polygon Point Circle real imag real imag 3D-Point

37 37 Why Inheritance ? Inheritance is a mechanism for building class types from existing class types defining new class types to be a specialization augmentation of existing types

38 38 Define a Class Hierarchy Syntax: class DerivedClassName : access-level BaseClassName where access-level specifies the type of derivation private by default, or public Any class can serve as a base class Thus a derived class can also be a base class

39 39 Class Derivation Point 3D-Point class Point{ protected: int x, y; public: void set (int a, int b); }; class 3D-Point : public Point{ private: double z; … }; class Sphere : public 3D-Point{ private: double r; … }; Sphere Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere

40 40 What to inherit? In principle, every member of a base class is inherited by a derived class just with different access permission

41 41 Access Control Over the Members Two levels of access control over class members class definition inheritance type class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ … };

42 42 The type of inheritance defines the access level for the members of derived class that are inherited from the base class Access Rights of Derived Classes privateprotectedpublic private--- protectedprivateprotected publicprivateprotectedpublic Type of Inheritance Access Controlfor Members

43 43 class daughter : --------- mother{ private: double dPriv; public: void mFoo ( ); }; Class Derivation class mother{ protected: int mProc; public: int mPubl; private: int mPriv; }; class daughter : --------- mother{ private: double dPriv; public: void dFoo ( ); }; void daughter :: dFoo ( ){ mPriv = 10; //error mProc = 20; }; private/protected/public int main() { /*….*/ } class grandDaughter : public daughter { private: double gPriv; public: void gFoo ( ); };

44 44 What to inherit? In principle, every member of a base class is inherited by a derived class just with different access permission However, there are exceptions for constructor and destructor operator=() member friends Since all these functions are class-specific

45 45 Constructor Rules for Derived Classes The default constructor and the destructor of the base class are always called when a new object of a derived class is created or destroyed. class A { public: A ( ) {cout<< “A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class B : public A { public: B (int a) {cout<<“B”<<endl;} }; B test(1); A:default B output:

46 46 Constructor Rules for Derived Classes You can also specify an constructor of the base class other than the default constructor class A { public: A ( ) {cout<< “A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class C : public A { public: C (int a) : A(a) {cout<<“C”<<endl;} }; C test(1); A:parameter C output: DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args ) { DerivedClass constructor body }

47 47 Define its Own Members Point Circle class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ private: double r; public: void set_r(double c); }; xyxy xyrxyr class Circle{ protected: int x, y; private: double r; public: void set(int a, int b); void set_r(double c); }; The derived class can also define its own members, in addition to the members inherited from the base class

48 48 Even more … A derived class can override methods defined in its parent class. With overriding, the method in the subclass has the identical signature to the method in the base class. a subclass implements its own version of a base class method. class A { protected: int x, y; public: void print () {cout<<“From A”<<endl;} }; class B : public A { public: void print () {cout<<“From B”<<endl;} };

49 49 class Point{ protected: int x, y; public: void set(int a, int b) {x=a; y=b;} void foo (); void print(); }; class Circle : public Point{ private: double r; public: void set (int a, int b, double c) { Point :: set(a, b); //same name function call r = c; } void print(); }; Access a Method Circle C; C.set(10,10,100); // from class Circle C.foo (); // from base class Point C.print(); // from class Circle Point A; A.set(30,50); // from base class Point A.print(); // from base class Point

50 50 Putting Them Together Time is the base class ExtTime is the derived class with public inheritance The derived class can inherit all members from the base class, except the constructor access all public and protected members of the base class define its private data member provide its own constructor define its public member functions override functions inherited from the base class ExtTimeTime

51 51 class Time Specification class Time{ public : void Set ( int h, int m, int s ) ; void Increment ( ) ; void Write ( ) const ; Time ( int initH, int initM, int initS ) ; // constructor Time ( ) ; // default constructor protected : int hrs ; int mins ; int secs ; } ; // SPECIFICATION FILE ( time.h)

52 52 Class Interface Diagram Protected data: hrs mins secs Set Increment Write Time Time class

53 53 Derived Class ExtTime // SPECIFICATION FILE ( exttime.h) #include “time.h” enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ; class ExtTime : public Time // Time is the base class and use public inheritance { public : void Set ( int h, int m, int s, ZoneType timeZone ) ; void Write ( ) const; //overridden ExtTime (int initH, int initM, int initS, ZoneType initZone ) ; ExtTime (); // default constructor private : ZoneType zone ; // added data member } ;

54 54 Class Interface Diagram Protected data: hrs mins secs ExtTime class Set Increment Write Time Set Increment Write ExtTime Private data: zone

55 55 Implementation of ExtTime Default Constructor ExtTime :: ExtTime ( ) { zone = EST ; } The default constructor of base class, Time(), is automatically called, when an ExtTime object is created. ExtTime et1; hrs = 0 mins = 0 secs = 0 zone = EST et1

56 56 Implementation of ExtTime Another Constructor ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone) : Time (initH, initM, initS) // constructor initializer { zone = initZone ; } ExtTime *et2 = new ExtTime(8,30,0,EST); hrs = 8 mins = 30 secs = 0 zone = EST et2 5000 ??? 6000 5000

57 57 Implementation of ExtTime void ExtTime :: Set (int h, int m, int s, ZoneType timeZone) { Time :: Set (hours, minutes, seconds); // same name function call zone = timeZone ; } void ExtTime :: Write ( ) const // function overriding { string zoneString[8] = {“EST”, “CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT”} ; Time :: Write ( ) ; cout <<‘ ‘<<zoneString[zone]<<endl; }

58 58 Working with ExtTime #include “exttime.h” … int main() { ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called thatTime.Write( ) ; // outputs 00:00:00 EST thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT thisTime.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST }

59 59 Inheritance Summary Inheritance is a mechanism for defining new class types to be a specialization or an augmentation of existing types. In principle, every member of a base class is inherited by a derived class with different access permissions, except for the constructors

60 ABSTRACT CLASS

61 Abstract Classes ● An abstract class (or abstract base class) is a class that contains pure virtual methods. ● A pure virtual method does not have a body. It is instead assigned a null value: classAnimal{ public: virtualvoidspeak()=0; ● }; ● Abstract base classes can only be used through inheritance ● It is impossible to create an instance of an abstract class

62 Abstract Classes & Pure Virtual Functions Some classes exist logically but not physically. Example : Shape Shape s; // Legal but silly..!! : “Shapeless shape” Shape makes sense only as a base of some classes derived from it. Serves as a “category” Hence instantiation of such a class must be prevented class Shape //Abstract { public : //Pure virtual Function virtual void draw() = 0; } A class with one or more pure virtual functions is an Abstract Class Objects of abstract class can’t be created Shape s; // error : variable of an abstract class

63 63 Example Shape virtual void draw() Circle public void draw() Triangle public void draw()

64 64 A pure virtual function not defined in the derived class remains a pure virtual function. Hence derived class also becomes abstract class Circle : public Shape { //No draw() - Abstract public : void print(){ cout << “I am a circle” << endl; } class Rectangle : public Shape { public : void draw(){ // Override Shape::draw() cout << “Drawing Rectangle” << endl; } Rectangle r; // Valid Circle c; // error : variable of an abstract class

65 65 Pure virtual functions : Summary Pure virtual functions are useful because they make explicit the abstractness of a class Tell both the user and the compiler how it was intended to be used. Note : It is a good idea to keep the common code as close as possible to the root of you hierarchy

66 66 Summary..continued It is still possible to provide definition of a pure virtual function in the base class. The class still remains abstract and functions must be redefined in the derived classes, but a common piece of code can be kept there to facilitate reuse. In this case, they can not be declared inline class Shape { //Abstract public : virtual void draw() = 0; }; // OK, not defined inline void Shape::draw(){ cout << “Shape" << endl; } class Rectangle : public Shape { public : void draw(){ Shape::draw(); //Reuse cout <<“Rectangle”<< endl; }

67 Polymorphism

68 68 Polymorphism – An Introduction noun, the quality or state of being able to assume different forms - Webster. An essential feature of an OO Language It builds upon Inheritance. Allows run-time interpretation of object type for a given class hierarchy Also Known as “Late Binding” Implemented in C++ using virtual functions

69 69 Dynamic Binding Is the run-time determination of which function to call for a particular object of a derived class based on the type of the argument Declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic binding Dynamic binding requires pass-by-reference

70 Polymorphism in C+ ● All polymorphism in C++ is done using inheritance; there is no concept of an interface A subclass is declared using the name of the class, a colon, the visibility of the parent class, and the name of the parent class: ● public: intx_pos; inty_pos; }; public: intradius; }; Class2DObject {Class { Circle:public2DObject

71 PolymorphismPolymorphism71 Virtual and Non-Virtual Overriding ● Overriding occurs when a child class has a method with the exact same type signature as one of the parent class methods Binding is the process of deciding whether to execute the parent's version or the child's version of a method The keyword virtual determines whether static binding or dynamic binding is used virtual only appears in the class definition ● ● ●

72 72 Virtual Functions Virtual Functions overcome the problem of run time object determination Keyword virtual instructs the compiler to use late binding and delay the object interpretation How ? Define a virtual function in the base class. The word virtual appears only in the base class If a base class declares a virtual function, it must implement that function, even if the body is empty Virtual function in base class stays virtual in all the derived classes It can be overridden in the derived classes But, a derived class is not required to re-implement a virtual function. If it does not, the base class version is used

73 A Class Hierarchy ● Consider the following class hierarchy: classAnimal{ public: virtual }; voidspeak() = 0;) = 0; classBird:publicAnimal{ public: virtual void speak() } {cout<< }; “twitter”; PolymorphismPolymorphism73

74 PolymorphismPolymorphism74 A Class Hierarchy cont. classCat:publicMammal{ public: voidspeak(){cout<<“meow!”;} virtualvoidpurr(){cout<<“purrrrr”;} }; classDog:publicMammal{ public: virtualvoidspeak(){cout<<“woof!”;} voidbark(){cout<<“woof!”;} }; classMammal : public Animal{ public: virtualvoid speak(){ cout<<“can'tspeak”;} voidbark() { cout<<“can'tbark”; };

75 Static Binding virtual is not used when declaring the method: voidbark() { cout<< “can'tbark”;} The decision is made at compile time based on the type of the variable: Dog*d=new Dog(); Mammal* m = d ; d->bark() ; //woof m->bark(); // can't bark.

76 Dynamic Binding ● virtual is used to declare the method: virtualvoidspeak(){ cout<<“woof!”; } The binding decision is made at run-time based on the type of the object: ● d->speak(); // woof! m->speak(); // woof! Animal *a= d; a->speak ();// woof!

77 Limitations The validity of calling a method is always static. If a method is not defined in a class or inherited from a parent class, it cannot be called: Overriding only works with heap-resident values: Dog*d=new Dog(); Animal*a=d; d->bark(); // woof! a->bark();// Compile error, not allowed. Mammalm =*d; m.speak(); // can't Speak

78 More Limitations ● Child classes cannot change the type of binding ● A method that is declared virtual in a parent class will always be virtual in a child class, even if virtual is not used in the child class Similarly, a method that is not declared virtual in the parent class can never be made virtual in the child class ● ● Any method that is called from a constructor cannot be overridden Virtual methods are never inlined ●

79 PolymorphismPolymorphism 79 Private and Protected Inheritance ● Usually inheritance is public Protected inheritance changes public members in the parent to protected in the child Private inheritance changes public and protected members to private ● ● classPig: { public: protectedMammal voidoink(){cout<<“Oink!”;} //Thespeak // andbarkmethodscanonlybe accessedbychildclasses. };

80 Virtual Destructors ● If any virtual methods are used, the destructor should be virtual to ensure that both the parent and child destructors are called class Bird public: virtual :publicAnimal{ ~Bird(){cout<< “birdkilled”;} }; class Duck public: virtual virtual :publicBird{ voidspeak(){cout <<“quack!”;} } ~Duck(){cout<<“duckkilled”; };

81 Polymorphism Example Please check the following example of polymorphismpolymorphism

82 82 Polymorphism Summary: When you use virtual functions, compiler store additional information about the types of object available and created Polymorphism is supported at this additional overhead Important : virtual functions work only with pointers/references Not with objects even if the function is virtual If a class declares any virtual methods, the destructor of the class should be declared as virtual as well.

83 83 So far, Polymorphism Polymorphism is built upon class inheritance It allows different versions of a function to be called in the same manner, with some overhead Polymorphism is implemented with virtual functions, and requires pass-by-reference

84 Overloading

85 Operator Overloading

86 A Rational Class ● Consider this class for storing rational numbers: classrational{ private: inttop; intbottom; }; public: rational(intt=0,intb=1) :top(t),bottom(b){} rational(constrational&r) :top(r.top),bottom(r.bottom){){} intnumerator()const{returntop;} intdenominator()const{returnbottom;}

87 An add function ● To implement addition with two rationals, the following could be added to the class definition: constrationaladd(constrational&r)const{ int int t=top*r.bottom+bottom*r.top; b=bottom*r.bottom; returnrational(t,b); } ● Now addition works: rationala(5,6); rationalb(2,3); rationalc=a.add(b);

88 A Better add Function ● The syntax of the add function could be better.It would be nicer (and make sense) to write: Rational c = a + b; ● Operator overloading makes this possible: co nstrationaloperator+(constrational r) const& { int t= top* r.bottom + bottom *r.top; int b=bottom * r.bottom; returnrational( t,b ); }

89 Operator Overloading89 ● Operator overloading allows existing C++ operators to work with user-defined data types. There are limits to this, however: ● ● At least one operand must be a user-defined type.It is impossible to change the meaning of 2 + 2. Cannot create new operators. Cannot change precedence and associativity. Don't change the meaning of an operator - operator+ should always do something similar to addition. ● ● ●

90 Overloaded Operators ) -> ->* new delete +&+& -|-| *~*~ /!/! % && ^ || ++--<<>>,< <===!=>>== +=-=*=/=%=&= |=^=<<=>>=[][](

91 Operator Overloading91 Functions and Methods ● Operators can generally be overloaded as member functions or global functions. ● Unary operators can be methods with no arguments or global functions with one argument. Binary operators can be methods with one argument or global functions with two arguments. ● ● Operators [], (), ->, and = must be methods. If used as I/O operators (as they usually are), >> and << must be global functions. ●

92 Binary Arithmetic Operators ● The result should be a new value. The return value should be constant so it cannot be the target of an assignment: (a+b) =b;//Thisshouldbeimpossible Parameters are values or constant references. ● ● The operands should not be modified. Methods should be declared constant: constrational operator/(constrational &r)const;

93 Binary Arithmetic Ops. cont. ● Subtraction as a method: constrational operator-( const rational&r) const{ intt= top * r.bottom – bottom * r.top; intb= bottom* r.bottom; returnrational(t,b); } ● Multiplication as a global function: const rational operator*( const rational & l, const rational & r ) { return rational(l.numerator( )*r.numerator(),l.denominator( ) * r.denominator( ) ); }

94 Comparison Operators Work like the binary arithmetic operators, except these return a boolean. Equals and less-than as methods: b ool operator==(constrational&r)const { returntop*r.bottom==bottom*r.top; } booloperator<( { constrational &r)const *r.top; returntop*r.bottom<bottom }

95 Increment and Decrement ● Can be prefix form (++i) or postfix form (i++). ● Prefix form increments and returns the new value: ● Postfix form increments but returns the original value: intc=a++;//a=7,c=6 ● Prefix increment for the rational as a method: constrational top =top+ operator++(){ bottom; return } inta=5; intb=a++;//a=6,b=6

96 Increment and Decrement cont. ● To distinguish postfix from prefix, the postfix version uses a dummy integer argument: constrationaloperator++(int) { rationaltemp=*this; top+= return bottom; temp; } constrationaloperator--(int){ rationaltemp=*this; top-= return bottom; temp; }

97 Assignment Operator ● The right operand is copied to the left operand. Should return a constant reference or a constant value to prevent a second assignment. Assignment operator for rational as a method: ● ● constrational&operator=(constrational&r) { top=r.top; bottom return =r.bottom; *this; }

98 Assignment Operator cont. The assignment operator will be provided by the compiler if the programmer doesn't write it The compiler version just copies the data members If the class has pointers to other values that should be copied, the programmer should write the assignment Common mistakes: Not returning a value Not handling self-assignment Simply copying pointers rather than making copies of the heap-resident values the object has pointers to


Download ppt "An Equal Opportunity University CS 215-401 Fall 2014 Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz Slide modified from Link 1 Link."

Similar presentations


Ads by Google