Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Inheritance and Member Functions: Overriding and Protected Access in C++, Slides of Computer Science

An introduction to inheritance in c++, focusing on the use of member functions in derived classes. Topics covered include public, protected, and private inheritance, base and derived classes, and the implementation of protected members. The document also discusses the concept of encapsulation and its implications for derived classes. Several code examples are provided to illustrate the concepts.

Typology: Slides

2012/2013

Uploaded on 03/20/2013

dharmanand
dharmanand 🇮🇳

3.3

(3)

61 documents

1 / 21

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 19 – Inheritance – Part 1
Outline
19.1 Introduction
19.2 Inheritance: Base Classes and Derived Classes
19.3 Protected Members
19.4 Casting Base-Class Pointers to Derived-Class Pointers
19.5 Using Member Functions
19.6 Overriding Base-Class Members in a Derived Class
19.7 Public, Protected and Private Inheritance
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Inheritance and Member Functions: Overriding and Protected Access in C++ and more Slides Computer Science in PDF only on Docsity!

Chapter 19 – Inheritance – Part 1

Outline

19.1 Introduction

19.2 Inheritance: Base Classes and Derived Classes

19.3 Protected Members

19.4 Casting Base-Class Pointers to Derived-Class Pointers

19.5 Using Member Functions

19.6 Overriding Base-Class Members in a Derived Class

19.7 Public, Protected and Private Inheritance

Docsity.com

19.1 Introduction

  • Inheritance
    • New classes created from existing classes
    • Absorb attributes and behaviors from base class.
  • Polymorphism
    • Write programs in a general fashion
    • Handle a wide variety of existing (and unspecified) related classes
  • Derived class
    • Class that inherits data members and member functions from a previously defined base class
    • Derived class extends the behavior of the base class.

Docsity.com

19.2 Base and Derived Classes

  • Often an object from a derived class (subclass) “is an” object of a base class (superclass) Base class Derived classes Student GraduateStudent UndergraduateStudent Shape Circle Triangle Rectangle Loan CarLoan HomeImprovementLoan MortgageLoan Employee FacultyMember StaffMember Account CheckingAccount SavingsAccount

Docsity.com

19.2 Base and Derived Classes (II)

  • 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

Docsity.com

19.4 Casting Base Class Pointers to Derived Class Pointers

  • Object of a derived class
    • Can be treated as an object of the base class
    • Reverse not true - base class objects not a derived- class object. (Unsafe)
  • Downcasting a pointer
    • Use an explicit cast to convert a base-class pointer to a derived-class pointer
    • Be sure that the type of the pointer matches the type of object to which the pointer points

derivedPtr = static_cast< DerivedClass * > basePtr;

Docsity.com

19.4 Casting Base-Class Pointers to Derived-Class Pointers (II)

  • Example
    • Circle class derived from the Point base class
    • We use pointer of type Point to reference a Circle object, and vice-versa

Docsity.com

1.1 Function definitions ---------------------

1. Circle class definition 34 y = b; 35 } 36 37 // Output Point (with overloaded stream insertion operator) 38 ostream &operator<<( ostream &output, const Point &p ) 39 { 40 output << '[' << p.x << ", " << p.y << ']'; 41 42 return output; // enables cascaded calls 43 } 44 // Fig. 19.4: circle.h 45 // Definition of class Circle 46 #ifndef CIRCLE_H 47 #define CIRCLE_H 48 49 #include 50 51 using std::ostream; 52 53 #include 54 55 using std::ios; 56 using std::setiosflags; 57 using std::setprecision; 58 59 #include "point.h" 60 61 class Circle : public Point { // Circle inherits from Point 62 friend ostream &operator<<( ostream &, const Circle & ); 63 public: 64 // default constructor

Docsity.com

**1. Circle definition

  1. Load header 1.1 Function Definitions** 65 Circle( double r = 0.0, int x = 0, int y = 0 ); 66 67 void setRadius( double ); // set radius 68 double getRadius() const; // return radius 69 double area() const; // calculate area 70 protected: 71 double radius; 72 }; 73 74 #endif 75 // Fig. 19.4: circle.cpp 76 // Member function definitions for class Circle 77 #include "circle.h" 78 79 // Constructor for Circle calls constructor for Point 80 // with a member initializer then initializes radius. 81 Circle::Circle( double r, int a, int b ) 82 : Point( a, b ) // call base-class constructor 83 { setRadius( r ); } 84 85 // Set radius of Circle 86 void Circle::setRadius( double r ) 87 { radius = ( r >= 0? r : 0 ); }

88 Docsity.com

1.1 Initialize objects 1.2 Assign objects

2. Function calls 134 cout << "\nCircle c (via *circlePtr):\n" << *circlePtr 135 << "\nArea of c (via circlePtr): " 136 << circlePtr->area() << '\n'; 137 138 // DANGEROUS: Treat a Point as a Circle 139 pointPtr = &p; // assign address of Point to pointPtr 140 141 // cast base-class pointer to derived-class pointer 142 circlePtr = static_cast< Circle * >( pointPtr ); 143 cout << "\nPoint p (via *circlePtr):\n" << *circlePtr 144 << "\nArea of object circlePtr points to: " 145 << circlePtr->area() << endl; 146 return 0; 147 } 122 Circle *circlePtr = 0, c( 2.7, 120, 89 ); 123 124 cout << "Point p: " << p << "\nCircle c: " << c << '\n'; 125 126 // Treat a Circle as a Point (see only the base class part) 127 pointPtr = &c; // assign address of Circle to pointPtr 128 cout << "\nCircle c (via *pointPtr): " 129 << *pointPtr << '\n'; 130 131 // Treat a Circle as a Circle (with some casting) 132 // cast base-class pointer to derived-class pointer 133 circlePtr = static_cast< Circle * >( pointPtr );

Docsity.com

Program Output Point p: [30, 50] Circle c: Center = [120, 89]; Radius = 2. Circle c (via *pointPtr): [120, 89] Circle c (via *circlePtr): Center = [120, 89]; Radius = 2. Area of c (via circlePtr): 22. Point p (via *circlePtr): Center = [30, 50]; Radius = 0. Area of object circlePtr points to: 0.

Docsity.com

19.6 Overriding Base-Class Members in a Derived Class

  • To override a base-class member function
    • In derived class, supply new version of that function
      • Same function name and signature , different definition
    • The scope-resolution operator may be used to access the base class version from the derived class

Docsity.com

1. Employee **class definition


  1. Load header 1.1 Function definitions** 1 // Fig. 19.5: employ.h 2 // Definition of class Employee 3 #ifndef EMPLOY_H 4 #define EMPLOY_H 5 6 class Employee { 7 public: 8 Employee( const char *, const char * ); // constructor 9 void print() const; // output first and last name 10 ~Employee(); // destructor 11 private: 12 char *firstName; // dynamically allocated string 13 char *lastName; // dynamically allocated string 14 }; 15 16 #endif 17 // Fig. 19.5: employ.cpp 18 // Member function definitions for class Employee 19 #include 20 21 using std::cout; 22 23 #include 24 #include 25 #include "employ.h" 26 27 // Constructor dynamically allocates space for the 28 // first and last name and uses strcpy to copy 29 // the first and last names into the object. 30 Employee::Employee( const char *first, const char *last ) 31 { 32 firstName = new char[ strlen( first ) + 1 ];

Docsity.com

1. Load header 1.1 Function definitions 64 double wage; // wage per hour 65 double hours; // hours worked for week 66 }; 67 68 #endif 69 // Fig. 19.5: hourly.cpp 70 // Member function definitions for class HourlyWorker 71 #include 72 73 using std::cout; 74 using std::endl; 75 76 #include 77 78 using std::ios; 79 using std::setiosflags; 80 using std::setprecision; 81 82 #include "hourly.h" 83 84 // Constructor for class HourlyWorker 85 HourlyWorker::HourlyWorker( const char *first, 86 const char *last, 87 double initHours, double initWage ) 88 : Employee( first, last ) // call base-class constructor 89 { 90 hours = initHours; // should validate 91 wage = initWage; // should validate 92 } 93 94 // Get the HourlyWorker's pay 95 double HourlyWorker::getPay() const { return wage * hours; }

Docsity.com

1.1 Function Definitions --------------------

**1. Load header 1.1 Initialize object

  1. Function call Program Output**

97 // Print the HourlyWorker's name and pay 98 void HourlyWorker::print() const 99 { 100 cout << "HourlyWorker::print() is executing\n\n"; 101 Employee::print(); // call base-class print function 102 103 cout << " is an hourly worker with pay of $" 104 << setiosflags( ios::fixed | ios::showpoint ) 105 << setprecision( 2 ) << getPay() << endl; 106 } 107 // Fig. 19.5: fig19_05.cpp 108 // Overriding a base-class member function in a 109 // derived class. 110 #include "hourly.h" 111 112 int main() 113 { 114 HourlyWorker h( "Bob", "Smith", 40.0, 10.00 ); 115 h.print(); 116 return 0; 117 } HourlyWorker::print() is executing

Bob Smith is an hourly worker with pay of $400.00 Docsity.com