Derived Classes in C++

Similar documents
Classes, Constructors, etc., in C++

And Even More and More C++ Fundamentals of Computer Science

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

Containers and the Standard Template Library (STL)

Iterators. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Exception Handling in C++

Your first C and C++ programs

Linked Lists in C and C++

Programming Assignment #4 Binary Trees in C++

Inheritance and Polymorphism

A Deeper Look at Classes

Inheritance (Deitel chapter 9)

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS105 C++ Lecture 7. More on Classes, Inheritance

VIRTUAL FUNCTIONS Chapter 10

Object-Oriented Design (OOD) and C++

Lecture 5: Inheritance

CMSC 132: Object-Oriented Programming II

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Structures, Unions, and Typedefs

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

C++ Important Questions with Answers

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Data Abstraction. Hwansoo Han

Binary Trees (and Big O notation)

Polymorphism Part 1 1

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

Fast Introduction to Object Oriented Programming and C++

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

10. Abstract Data Types

Arrays and Pointers in C & C++

Module 10 Inheritance, Virtual Functions, and Polymorphism

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

History C++ Design Goals. How successful? Significant constraints. Overview of C++

Evolution of Programming Languages

Lecture Notes on Programming Languages

Constructors for classes

Today s lecture. CS 314 fall 01 C++ 1, page 1

Financial computing with C++

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Inheritance -- Introduction

Instantiation of Template class

Object Oriented Paradigm

Chapter 11. Abstract Data Types and Encapsulation Concepts

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

BBM 102 Introduction to Programming II Spring Inheritance

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Computer Programming Inheritance 10 th Lecture

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Where do we go from here?

Lecture 18 CSE11 Fall 2013 Inheritance

Inheritance and Interfaces

Inheritance (with C++)

Inheritance Basics. Inheritance (with C++) Base class example: Employee. Inheritance begets hierarchies. Writing derived classes

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

CSE 303: Concepts and Tools for Software Development

CS304 Object Oriented Programming

Object Oriented Programming. Solved MCQs - Part 2

CSE 307: Principles of Programming Languages

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

CMSC 132: Object-Oriented Programming II

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

Programming II (CS300)

C++ Yanyan SHEN. slide 1

Virtual functions concepts

Practice for Chapter 11

Programming, numerics and optimization

ECE 3574: Dynamic Polymorphism using Inheritance

CS111: PROGRAMMING LANGUAGE II

An Introduction to C++

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Chapter 10 :: Data Abstraction and Object Orientation

04-24/26 Discussion Notes

CS250 Final Review Questions

C++ Inheritance and Encapsulation

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

Objects, Encapsulation, Inheritance (2)

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

CS11 Introduction to C++ Fall Lecture 7

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

Interview Questions of C++

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

And Even More and More C++ Fundamentals of Computer Science

(11-1) OOP: Inheritance in C++ D & D Chapter 11. Instructor - Andrew S. O Fallon CptS 122 (October 29, 2018) Washington State University

EL2310 Scientific Programming

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Programming in C and C++

C++ Programming for Programmers using Microsoft Visual C Professional

MaanavaN.Com CS1203 OBJECT ORIENTED PROGRAMMING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

6.S096 Lecture 10 Course Recap, Interviews, Advanced Topics

Inheritance. OOP: Inheritance 1

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1

C10: Garbage Collection and Constructors

Transcription:

Derived Classes in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel) 1

Outline Introduction Base Classes and Derived Classes Some Examples of Base Class and Derived Class Relationships Constructors and Destructors in Derived Classes Accessing Members of Base and Derived Classes 2

Reading Assignment Absolute C++, Chapter 14 A lot of similarities to Java Some differences 3

History The whole notion of classes, subclasses, and inheritance came from Simula 67 A generalization of notion of records (now known as structs) from Algol- and Pascal-like languages in 1960s and early 70s A (very nice) programming language developed in Norway for implementing large simulation applications 4

Terminology Inheritance is a form of software reuse where a new class is created to absorb an existing class s data and behaviors, and enhance them with new capabilities The new class, the derived class, inherits the members of the existing class, known as the base class 5

Terminology (continued) C++ Derived Class Java Subclass Base Class Superclass Abstract Class Abstract Class Virtual Function Abstract Method 6

Terminology (continued) A direct base class is the base class from which a derived class explicitly inherits. An indirect base class is inherited from two or more levels up in the class hierarchy. In single inheritance, a class is derived from one base class. With multiple inheritance, a derived class inherits from multiple base classes. 7

Class Hierarchy 8

Another Class Hierarchy Note two separate base classes 9

Types of Inheritance in C++ public: every object of a derived class is also an object of its base class Note, base-class objects are NOT objects of their derived classes. private: is essentially an alternative to composition I.e., derived class members not accessible from outside protected: not frequently used 10

Example public class class Employee { string givenname, familyname; date hiringdate; short department;... }; class Manager: public Employee { set <Employee *> group; short level;... } 11

Example public class class Employee { string givenname, familyname; date hiringdate; short department;... }; class Manager: public Employee { set <Employee *> group; short level;... } Note: this is an example of the use of a container class from Standard Template Library 12

Important Note Member functions of derived class cannot directly access private members of base class Example: Manager member functions in previous example cannot read manager s own name! Because data members of a class are by default private 13

protected: Access Specifier class Employee { protected: string givenname, familyname; date hiringdate; short department;... }; class Manager: public Employee { set <Employee *> group; short level;... } 14

protected (continued) A base class s protected members can be accessed by members and friends of the base class, and members and friends of any class derived from the base class. Derived-class member functions can refer to public and protected members of the base class. By simply using their names 15

Difference between Inheritance and Composition is-a relationship: inheritance e.g., derived class object, car, is an object of the base class vehicle e.g., derived class object, Manager, is an object of the base class Employee has-a relationship: composition e.g., a TreeNode object has (i.e., contains) a member object of type string 16

Base Classes and Derived Classes Base classes typically represent larger sets of objects than derived classes Example Base class: vehicle Includes cars, trucks, boats, bicycles, etc. Derived class: car a smaller, more-specific subset of vehicles 17

Base Classes and Derived Classes (continued) I.e., base classes have more objects But fewer data and function members Derived classes have only subsets of the objects Hence the term subclass But a derived class may have more members both data and function members 18

Questions? 19

Digression Code Re-use Fundamental principle of software engineering A body of code is a living, evolving thing As a practical matter, copies of code cannot keep up with each other If you really want your hard work to support multiple purposes, applications, requirements, etc. You really need a way for those purposes to inherit your code rather than copy it. 20

Constructors and Destructors Constructor: Derived class constructor is called to create derived class object Invokes base class constructor first Before derived class initializer list & constructor body and so on up class hierarchy Destructor: Derived class destructor body is executed first Then destructors of derived class members And then destructor of base class and so on up class hierarchy 21

Instantiating a Derived-class Object Derived-class constructor invokes base class constructor either implicitly (via a base-class member initializer) or explicitly (by calling the base classes default constructor) Base of inheritance hierarchy Last constructor called in inheritance chain is at base of hierarchy Last constructor is first constructor body to finish executing 22

Example class Employee { string name; int dept; public: Employee(const string s, int d); } class Manager: public Employee { int level; public: Manager(const string s, int d, int lvl); } Employee::Employee (const string s, int d): name(s), dept(d) { } Manager::Manager (const string s, int d, int lvl): Employee(s, d), level(lvl) { } 23

Recap Worcester Polytechnic Carnegie Institute Mellon Absolute C++, 14.1 When creating a derived-class object: Derived-class constructor immediately calls base-class constructor Base-class constructor executes Derived class member initializers execute (Finally) derived-class constructor body executes If your constructor does not invoke the base class constructor explicitly, the compiler will generate code to invoke the base class default constructor as first step in initialization 24

Recap Worcester Polytechnic Carnegie Institute Mellon Absolute C++, 14.1 When creating a derived-class object: Derived-class constructor immediately calls base-class constructor Base-class constructor executes Derived class member initializers execute (Finally) derived-class constructor body executes This process cascades up the hierarchy if the hierarchy contains more than two levels. 25

Constructors and Destructors in Derived Classes Destroying derived-class objects Reverse order of constructor chain Destructor of derived-class called first Destructor of next base class up hierarchy is called next This continues up hierarchy until the final base class is reached. After final base-class destructor, the object is removed from memory Base-class constructors, destructors, and overloaded assignment operators are not inherited by derived classes. 26

Remember When a class contains members of other classes contructors of those members are called before class contructor body Either in initializer list or by default Apply same rule to members of base class! 27

Remember Destructors for derived-class objects are called in reverse order from which corresponding constructors were called. 28

Questions? 29

Redefinition of Base Class Members Suppose that base class has a member E.g. void print() Knows only how to print information from base class Define same member in derived class E.g. void print() Knows how to print info for derived class Needs to call base class print() function to print base class info 30

Redefinition of Base Class Members (continued) Derived class void print() { // print derived class info BaseClass::print(); //prints base info } // more derived class stuff See Absolute C++, 14.1 General principle: when in derived class scope, if you need to access anything in base class with a naming conflict, use '::' scope resolution operator 31

Accessing Members of Base and Derived Classes Let B be a base class with public members m and n Let D be a derived class with public members m and p I.e., D redefines member m E.g., print() function of previous example Consider the following: B objb; D objd; B *ptrb; D *ptrd; Copy to white board! 32

Accessing Members (continued) objb.m and objb.n are both legal access members of base class objd.m and objd.p are both legal access members of derived class objd.n is also legal accesses member of base class! objb.p is not legal Class B has no member named p! 33

Accessing Members (continued) ptrb = new B(); ptrb -> m and ptrb -> n are both legal access members of base class ptrd = new D(); ptrd -> m and ptrd -> p are both legal access members of derived class 34

Accessing Members (continued) ptrb = ptrd; ptrb now points to an object of the derived class which by definition is an object of the base class! ptrb -> m and ptrb -> n are both legal access members of base class object Even though object pointed to is an object of derived class, with its own redefined member m! 35

Accessing Members (continued) ptrb = ptrd; ptrb -> p is not legal Because ptrb only knows about B s members! Rule: So far, which member to access depends entirely on the type of the accessing pointer (or accessing object) To bend that rule, need polymorphism and virtual members. 36

Questions? 37

Loose End: Three Types of Inheritance in C++ public: every object of a derived class is also an object of its base class Note, base-class objects are NOT objects of their derived classes. private: is essentially an alternative to composition I.e., derived class members not accessible from outside protected: not often used 38

Let D be derived from B If B is a private base class: I.e., class D: private B {} Public and protected members of B can only be used by member and friend functions of D. Only members and friends of D can convert D* into B* Outside of member and friend functions of D Dptr -> p is not allowed (where p is a member of B) Bptr = Dptr is not allowed 39

Let D be derived from B (continued) If B is a protected base: I.e., class D: protected B {} Public and protected members of B can only be used by member and friend functions of D and also by member and friend functions of classes derived from D Only members and friends of D and its derived classes can convert D* into B* I.e., outside of member and friend functions of D or its derived classes Dptr -> p is not allowed (where p is a member of B) Bptr = Dptr is not allowed 40

Let D be derived from B (continued) If B is a public base: I.e., class D: public B {} Public members of B can be used by any function Protected members of B can be used by member and friend functions of D and also by member and friend functions of classes derived from D Any function can convert D* into B* I.e., Dptr -> p is allowed (where p is a member of B) Bptr = Dptr is allowed 41

Summary Inheritance This topic covered the basics of inheritance in C++ There is much, much more to say about inheritance after we cover polymorphism 43

Questions? Next Topic 44