EECE 330 Notes Classes, Fall 2013

American University of Beirut · Data Structures and Algorithms · 35 pages

All EECE 330 files
EECE 330 Notes Classes, Fall 2013, page 1

Stuck on a question? A tutor can walk you through it.

EECE 330 Notes Classes, Fall 2013, page 2 EECE 330 Notes Classes, Fall 2013, page 3 EECE 330 Notes Classes, Fall 2013, page 4 EECE 330 Notes Classes, Fall 2013, page 5 EECE 330 Notes Classes, Fall 2013, page 6 EECE 330 Notes Classes, Fall 2013, page 7 EECE 330 Notes Classes, Fall 2013, page 8 EECE 330 Notes Classes, Fall 2013, page 9 EECE 330 Notes Classes, Fall 2013, page 10

Showing the first 10 of 35 pages. Download the PDF to see all of it.

More EECE 330 files

Show the text of this notes
H. Artail – EECE330 (Review) 1 Classes, Inheritance, and Virtual Functions EECE 230 Material Review C++ How To Program (by Deitel & Deitel) Chapters 6, 7, 9, and 10 H. Artail – EECE330 (Review) 2 Defining Member Functions and Accessing Class Members • Binary scope resolution operator (::) – Combines the class name with the member function name – Different classes can have member functions with the same name • Format for defining member functions ReturnType ClassName::MemberFunctionName( ){ … } • Accessing class members – Dot (.) for objects and arrow (->) for pointers – Example: • t.hour is the hour element of the object t • TimePtr->hour is the hour element of the object pointed to by TimePtr H. Artail – EECE330 (Review) 3 Controlling Access to Members • public – Presents clients with a view of the services the class provides (interface) – Data and member functions are accessible • private – Default access mode – Data only accessible to member functions and friends – private members only accessible through the public class interface using public member functions H. Artail – EECE330 (Review) 4 Access Functions and Utility Functions • Utility functions – private functions that support the operation of public functions – Not intended to be used directly by clients • Access functions – public functions that read/display data or check conditions – Allow public functions to check private data H. Artail – EECE330 (Review) 5 6.10 Initializing Class Objects: Constructors • Constructors – Initialize class members – Same name as the class – No return type – Member variables can be initialized by the constructor or set afterwards • Passing arguments to a constructor – When an object of a class is declared, initializers can be provided – Format of declaration with initializers: Class-type ObjectName( value1,value2,…); – Default arguments may also be specified in the constructor prototype H. Artail – EECE330 (Review) 6 6.12 Using Destructors • Destructors – Are member function of class – Perform termination housekeeping before the system reclaims the object’s memory – Complement of the constructor – Name is tilde (~) followed by the class name (i.e., ~Time) • Recall that the constructor’s name is the class name – Receives no parameters, returns no value – One destructor per class • No overloading allowed H. Artail – EECE330 (Review) 7 When Constructors and Destructors Are Called • Constructors and destructors called automatically – Order depends on scope of objects • Global scope objects – Constructors called before any other function (including main) – Destructors called when main terminates (or exit function called) – Destructors not called if program terminates with abort • Automatic local objects – Constructors called when objects are defined – Destructors called when objects leave scope • i.e., when the block in which they are defined is exited – Destructors not called if the program ends with exit or abort H. Artail – EECE330 (Review) 8 When Constructors and Destructors Are Called • Static local objects – Constructors called when execution reaches the point where the objects are defined – Destructors called when main terminates or the exit function is called – Destructors not called if the program ends with abort H. Artail – EECE330 (Review) 9 Using Data Members and Member Functions • Member functions – Allow clients of the class to set (i.e., write) or get (i.e., read) the values of private data members – Example: Adjusting a customer’s bank balance • private data member balance of a class BankAccount could be modified through the use of member function computeInterest • A member function that sets data member interestRate could be called setInterestRate, and a member function that returns the interestRate could be called getInterestRate – Providing set and get functions does not make private variables public – A set function should ensure that the new value is valid H. Artail – EECE330 (Review) 10 Returning a Reference to a Private Data Member • Reference to an object – Alias for the name of the object – May be used on the left side of an assignment statement – Reference can receive a value, which changes the original object as well • Returning references – public member functions can return non-const references to private data members • Should be avoided, breaks encapsulation H. Artail – ELEG 055C (Review) 11 1 // Fig. 6.11: time4.h 2 // Declaration of the Time class. 3 // Member functions defined in time4.cpp 4 5 // preprocessor directives that 6 // prevent multiple inclusions of header file 7 #ifndef TIME4_H 8 #define TIME4_H 9 10 class Time { 11 public: 12 Time( int = 0, int = 0, int = 0 ); 13 void setTime( int, int, int ); 14 int getHour(); 15 int &badSetHour( int ); // DANGEROUS reference return 16 private: 17 int hour; 18 int minute; 19 int second; 20 }; 21 22 #endif Notice how member function badSetHour returns a reference (int & is the return type). H. Artail – ELEG 055C (Review) 12 23 // Fig. 6.11: time4.cpp 24 // Member function definitions for Time class. 25 #include "time4.h" 26 27 // Constructor function to initialize private data. 28 // Calls member function setTime to set variables. 29 // Default values are 0 (see class definition). 30 Time::Time( int hr, int min, int sec ) 31 { setTime( hr, min, sec ); } 32 33 // Set the values of hour, minute, and second. 34 void Time::setTime( int h, int m, int s ) 35 { 36 hour = ( h >= 0 && h < 24 ) ? h : 0; 37 minute = ( m >= 0 && m < 60 ) ? m : 0; 38 second = ( s >= 0 && s < 60 ) ? s : 0; 39 } 40 41 // Get the hour value 42 int Time::getHour() { return hour; } 43 44 // POOR PROGRAMMING PRACTICE: 45 // Returning a reference to a private data member. 46 int &Time::badSetHour( int hh ) 47 { 48 hour = ( hh >= 0 && hh < 24 ) ? hh : 0; 49 50 return hour; // DANGEROUS reference return 51 } badSetHour returns a reference to the private member variable hour. Changing this reference will alter hour as well. H. Artail – ELEG 055C (Review) 13 52 // Fig. 6.11: fig06_11.cpp 53 // Demonstrating a public member function that 54 // returns a reference to a private data member. 55 // Time class has been trimmed for this example. 56 #include <iostream> 57 58 using std::cout; 59 using std::endl; 60 61 #include "time4.h" 62 63 int main() 64 { 65 Time t; 66 int &hourRef = t.badSetHour( 20 ); 67 68 cout << "Hour before modification: " << hourRef; 69 hourRef = 30; // modification with invalid value 70 cout << "\nHour after modification: " << t.getHour(); 71 72 // Dangerous: Function call that returns 73 // a reference can be used as an lvalue! 74 t.badSetHour(12) = 74; 75 cout << "\n\n*********************************\n" 76 << "POOR PROGRAMMING PRACTICE!!!!!!!!\n" 77 << "badSetHour as an lvalue, Hour: " 78 << t.getHour() 79 << "\n*********************************" << endl; 80 81 return 0; 82 } Declare Time object t and reference hourRef that is assigned the reference returned by the call t.badSetHour(20). Alias used to set the value of hour to 30 (an invalid value). Function call used as an lvalue and assigned the value 74 (another invalid value). Hour before modification: 20 Hour after modification: 30 ********************************* POOR PROGRAMMING PRACTICE!!!!!!!! badSetHour as an lvalue, Hour: 74 ********************************* H. Artail – EECE330 (Review) 14 const (Constant) Objects and const Member Functions • Use of const functions – Member functions declared const cannot modify their object – const must be specified in function prototype and definition – Prototype: ReturnType FunctionName(param1,param2…) const; – Definition: ReturnType FunctionName(param1,param2…) const { …} – Example: int A::getValue() const { return privateDataMember }; • Returns the value of a data member but doesn’t modify anything so is declared const • Constructors / Destructors cannot be const – They need to initialize variables, therefore modifying them H. Artail – EECE330 (Review) 15 const (Constant) Objects and const Member Functions • Member initializer syntax – Constant data member increment in class Increment – constructor for Increment is modified as follows: Increment::Increment( int c, int i ) : increment( i ) { count = c; } – : increment( i ) initializes increment to i – All data members can be initialized using member initializer syntax – consts and references must be initialized using member initializer syntax – Multiple member initializers • Use comma-separated list after the colon H. Artail – EECE330 (Review) 16 friend Functions and friend Classes • friend function and friend classes – Can access private and protected members of another class – friend functions are not member functions of class • Defined outside of class scope H. Artail – EECE330 (Review) 17 friend Functions and friend Classes • friend declarations – To declare a friend function • Type friend before the function prototype in the class that is giving friendship friend int myFunction( int x ); should appear in the class giving friendship – To declare a friend class • Type friend class Classname in the class that is giving friendship • if ClassOne is granting friendship to ClassTwo, friend class ClassTwo; • should appear in ClassOne's definition H. Artail – EECE330 (Review) 18 class CRectangle { int width, height; public: void set_values (int, int); int area () {return (width * height);} friend CRectangle duplicate (CRectangle); }; void CRectangle::set_values (int a, int b) { width = a; height = b; } CRectangle duplicate (CRectangle rectparam) { CRectangle rectres; rectres.width = rectparam.width*2; rectres.height = rectparam.height*2; return (rectres); } int main () { CRectangle rect, rectb; rect.set_values (2,3); rectb = duplicate (rect); class CRectangle { int width, height; public: int area () {return (width * height);} void convert (CSquare a); }; class CSquare { private: int side; public: void set_side (int a) {side=a;} friend class CRectangle; }; void CRectangle::convert (CSquare a) { width = a.side; height = a.side; } int main () { CSquare sqr; H. Artail – EECE330 (Review) 19 Dynamic Memory Allocation with Operators new and delete • new and delete – Used for dynamic memory allocation – new • Creates an object of the proper size, calls its constructor and returns a pointer of the correct type – delete • Destroys object and frees space – Examples of new TypeName *typeNamePtr; • Creates pointer to a TypeName object typeNamePtr = new TypeName; • new creates TypeName object and returns a pointer to it H. Artail – EECE330 (Review) 20 Dynamic Memory Allocation with Operators new and delete – Examples of delete delete typeNamePtr; • Calls destructor for TypeName object and frees memory Delete [] arrayPtr; • Used to dynamically delete an array • Initializing objects double *thingPtr = new double( 3.14159 ); – Initializes object of type double to 3.14159 int *arrayPtr = new int[ 10 ]; – Creates a ten element int array and assigns it to arrayPtr H. Artail – EECE330 (Review) 21 static Class Members • static class members – Shared by all objects of a class • Normally, each object gets its own copy of each variable – Efficient when a single copy of data is enough • Only the static variable has to be updated – May seem like global variables, but have class scope • only accessible to objects of same class – Initialized at file scope – Exist even if no instances (objects) of the class exist – Both variables and functions can be static – Can be public, private or protected H. Artail – EECE330 (Review) 22 static Class Members • static variables – Static variables are accessible through any object of the class – public static variables • Can also be accessed using scope resolution operator(::) Employee::count – private static variables • When no class member objects exist, can only be accessed via a public static member function – To call a public static member function combine the class name, the :: operator and the function name Employee::getCount() • Static functions – static member functions cannot access non-static data or functions H. Artail – EECE330 (Review) 23 Inheritance – New classes created from existing classes – Absorb attributes and behaviors – Derived class • Class that inherits data members and member functions from a previously defined base class – Single inheritance • Class inherits from one base class – Multiple inheritance • Class inherits from multiple base classes – Types of inheritance • public: Derived objects are accessible by the base class objects • private: Derived objects are inaccessible by the base class • protected: Derived classes and friends can access protected members of the base class H. Artail – EECE330 (Review) 24 Inheritance: Base and Derived Classes • Base and derived classes – Often an object from a derived class (subclass) is also an object of a base class (superclass) • A rectangle is a derived class in reference to a quadrilateral and a base class in reference to a square • Inheritance examples Base class Derived classes Student GraduateStudent UndergraduateStudent Shape Circle Triangle Rectangle Loan CarLoan HomeImprovementLoan MortgageLoan Employee FacultyMember StaffMember Account CheckingAccount SavingsAccount H. Artail – EECE330 (Review) 25 Inheritance: Base and Derived Classes • Implementation of public inheritance class CommissionWorker : public Employee { ... }; – Class CommissionWorker inherits from class Employee – friend functions not inherited – private members of base class not accessible from derived class H. Artail – EECE330 (Review) 26 protected Members • protected access – Intermediate level of protection between public and private inheritance – Derived-class members can refer to public and protected members of the base class simply by using the member names H. Artail – EECE330 (Review) 27 Casting Base-Class Pointers to Derived Class Pointers • Derived classes relationships to base classes – Objects of a derived class can be treated as objects of the base class – Reverse not true: base class objects cannot be derived-class objects • Downcasting a pointer – Use an explicit cast to convert a base-class pointer to a derived- class pointer – If pointer is going to be dereferenced, the type of the pointer must match the type of object to which the pointer points – Format: derivedPtr = (DerivedClass *) basePtr; H. Artail – EECE330 (Review) 28 Overriding Base-Class Members in a Derived Class • To override a base-class member function – In the derived class, supply a new version of that function with the same signature • same function name, different definition – When the function is then mentioned by name in the derived class, the derived version is automatically called – The scope-resolution operator may be used to access the base class version from the derived class H. Artail – EECE330 (Review) 29 Using Constructors and Destructors in Derived Classes • Base class initializer – Uses member-initializer syntax – Can be provided in the derived class constructor to call the base-class constructor explicitly • Otherwise base class’s default constructor called implicitly – Base-class constructors and base-class assignment operators are not inherited by derived classes • Derived-class constructors and assignment operators, however, can call base-class constructors and assignment operators H. Artail – EECE330 (Review) 30 Using Constructors and Destructors in Derived Classes • A derived-class constructor – Calls the constructor for its base class first to initialize its base-class members – If the derived-class constructor is omitted, its default constructor calls the base-class’ default constructor • Destructors are called in the reverse order of constructor calls – So a derived-class destructor is called before its base-class destructor H. Artail – EECE330 (Review) 31 virtual Functions • virtual functions – Suppose a set of shape classes such as Circle, Triangle, etc. – Every shape has own unique draw function but possible to call them by calling the draw function of base class Shape • Compiler determines dynamically (i.e., at run time) which to call – In base-class declare draw to be virtual – Override draw in each of the derived classes – virtual declaration: • Keyword virtual before function prototype in base-class virtual void draw() const; – A base-class pointer to a derived class object will call the correct draw function Shape->draw(); – If a derived class does not define a virtual function, the function is inherited from the base class H. Artail – EECE330 (Review) 32 Virtual Functions ShapePtr->Draw(); – Compiler implements dynamic binding – Function determined during execution time ShapeObject.Draw(); – Compiler implements static binding – Function determined during compile-time H. Artail – EECE330 (Review) 33 Abstract and Concrete Classes • Abstract classes – Sole purpose is to provide a base class for other classes – No objects of an abstract base class can be instantiated • Too generic to define real objects (i.e., TwoDimensionalShape) • Can have pointers and references • Concrete classes – Classes that can instantiate objects – Provide specifics to make real objects (i.e., Square, Circle) • Making abstract classes – Declare one or more virtual functions as “pure” by initializing the function to zero – Example of a pure virtual function: virtual double earnings() const = 0; H. Artail – EECE330 (Review) 34 Polymorphism • Polymorphism – Ability for objects of different classes to respond differently to the same function call – Implemented through virtual functions • Base-class pointer (or reference) calls a virtual function • C++ chooses the correct overridden function in object – If non-virtual member function defined in multiple classes and called from base-class pointer then the base-class version is used • If called from derived-class pointer then derived-class version is used – Suppose print is not a virtual function Employee e, *ePtr = &e; HourlyWorker h, *hPtr = &h; ePtr->print(); // call base-class print function hPtr->print(); // call derived-class print function ePtr=&h; // allowable implicit conversion ePtr->print(); // still calls base-class print H. Artail – EECE330 (Review) 35 Virtual Destructors • Problem: – If a base-class pointer to a derived object is deleted, the base- class destructor will act on the object • Solution: – declare a virtual base-class destructor to ensure that the appropriate destructor will be called