CS Lecture #6. Administrative... Assignment #2 Graded NN Turned In, Average Grade: XX Assignment #3 due on Thursday

Similar documents
Lecture 11. Demonstration #1. More Inheritance, More Constructors. Absolute C++ Chapter 15. Virtual Functions. Overriding

CS Lecture #14

Arrays in C++ Instructor: Andy Abreu

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

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

Inheritance, and Polymorphism.

CS 162, Lecture 25: Exam II Review. 30 May 2018

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

Polymorphism. Arizona State University 1

Written by John Bell for CS 342, Spring 2018

Extending Classes (contd.) (Chapter 15) Questions:

C++ Inheritance and Encapsulation

CSCI 104 Polymorphism. Mark Redekopp David Kempe

Polymorphism. Contents. Assignment to Derived Class Object. Assignment to Base Class Object

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Virtual functions concepts

Increases Program Structure which results in greater reliability. Polymorphism

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

To become familiar with array manipulation, searching, and sorting.

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

Design Patterns: State, Bridge, Visitor

CPSC 427: Object-Oriented Programming

Inheritance and Polymorphism

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

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

Object-Oriented Programming, Iouliia Skliarova

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

Object-Oriented Concept

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Software Design and Analysis for Engineers

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

Writing Functions in C

Inheritance and Polymorphism

6.096 Introduction to C++

void Transaction::print() { cout << "Name: " << name << " Amount: " << amount << endl; }

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Polymorphism Part 1 1

A class is a user-defined type. It is composed of built-in types, other user-defined types and

Fast Introduction to Object Oriented Programming and C++

Inheritance Ch

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

CSE 333 Final Exam 3/19/14

We first learn one useful option of gcc. Copy the following C source file to your

explicit class and default definitions revision of SC22/WG21/N1582 =

Short Notes of CS201

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

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

CSCI 102 Fall 2010 Exam #1

CSE 303: Concepts and Tools for Software Development

What are the characteristics of Object Oriented programming language?

Financial computing with C++

CS201 - Introduction to Programming Glossary By

Pointers. Reference operator (&) ted = &andy;

Software Design and Analysis for Engineers

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

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

Lecture Topics. Administrivia

Type Checking in COOL (II) Lecture 10

Pointers, Arrays and Parameters

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

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

C++ Programming: Polymorphism

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

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

CS24 Week 3 Lecture 1

VIRTUAL FUNCTIONS Chapter 10

C:\Temp\Templates. Download This PDF From The Web Site

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

Variables. Data Types.

Rules and syntax for inheritance. The boring stuff

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Data Structures using OOP C++ Lecture 3

CS11 Introduction to C++ Fall Lecture 7

Lecture Transcript While and Do While Statements in C++

CS 103 Unit 11. Linked Lists. Mark Redekopp

Chapter 15. Polymorphism and Virtual Functions. Copyright 2010 Pearson Addison-Wesley. All rights reserved

CS558 Programming Languages

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

CSE 143 Lecture 12 Inheritance

What is an algorithm?

Lecture 02, Fall 2018 Friday September 7

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

Object-Oriented Programming (OOP) Fundamental Principles of OOP

QUIZ Friends class Y;

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

COMP322 - Introduction to C++

Inheritance. Chapter 15 & additional topics

Absolute C++ Walter Savitch

Chapter 10 :: Data Abstraction and Object Orientation

CS 351 Design of Large Programs Coding Standards

11. Abstract Classes and Interfaces

Transcription:

CS 213 -- Lecture #6 Late Night Guide to C++ Chapter 5 INHERITANCE Administrative... Assignment #2 Graded NN Turned In, Average Grade: XX Assignment #3 due on Thursday The Conceptual Side of Classes Earlier we defined classes as a user defined data type It could have member functions It could have member variables This is a technical, concrete definition The conceptual definition of classes is just that--it s a concept Usually a noun trees, birds, people, a person, dog, food, hot dogs, computers, etc. Verbs don t usually make good classes thinking, running, listening, laughing, crying When we define a class, we re providing a description for a class of things. A variable or instance of a class is thought of as one member of the class. For example: The Conceptual Side of Classes (cont) When we define a Student we might do the following: class Student string localphone; Here we have defined a class of people a Student When we allocate a variable of type Student We actually create one member of the class Student. Hmmm a class of people The Conceptual Side of Classes (cont) Sometimes multiple classes have similarities: class Student string localphone; class Instructor string employeeid; The Conceptual Side of Classes (cont) Sometimes the similarities are common to a broader class than the class being defined In the case of Student and Instructor, consider the common fields: name address phone Suppose we create a class called Person, as follows: 1

The Conceptual Side of Classes (cont) Now maybe you d think that we could do this: class Student Person imaperson; class Instructor Person imaperson; int employeeid; We can, in fact do this. But then any instance would have to access fields in Person through the imaperson member variable. Inheritance A better way to do this is with Inheritance In C++, when one class inherits another all public (and protected) member variables in the base class are accessible from the derived class as if they were declared right in the derived class. In our example: Person is the base class Student is the derived class To declare Student as being a derivation of Person, do this: class Student : public Person class Instructor : public Person int employeeid; Now, given the following declarations: string localphone; class Student : public Person Inheritance (cont) Inheritance (cont) astudent.name = Jon Doe ; // Defined in Person astudent.address = 12 Park Place ; // Defined in Person astudent.phone = 555-1212 ; // Defined in Person astudent.studentid = 442221; // Defined in Student Let s see this in action: We can write the following code: Demonstration #1 Simple Inheritance Protected Members A derived class may access any of the public members of the base class, and so can anyone else using the base class directly. A derived class may NOT access any of the private members of the base class, nor may anyone else using the base class directly. A derived class may access any of the protected members of the base class, but no one using the base class directly may access them. To mark a member variable or function as protected, do the following: protected: 2

To clarify, when a member function or variable follows a protected keyword: Only member functions defined in a derived class may access the protected member functions/variables in the base class All other classes (not derived from the base class) may not access the protected member functions/variables Let s look at some code: protected: Now Consider a Derived Class.. class Student: public Person void printinfo(); int getid() return studentid; cout << Name: << name << endl; // name, address and cout << Addr: << address << endl; // phone are defined cout << Phone: << phone << endl; // in the base class Finally, let s use it... But they can be accessed inside of the derived class astudent.name = Joe Student ; //?? astudent.address = 166 Phelps Lane ; //?? astudent.phone = 555-1212 ; //?? astudent.printinfo(); Since name, address and phone are declared as protected members of the Person class They cannot be accessed outside of the class cout << Name: << name << endl; // name, address and cout << Addr: << address << endl; // phone are defined cout << Phone: << phone << endl; // in the base class The Person class had its own public method for setting info: void Person::setInfo(string Name,string Addr,string Phone) name = Name; addr = Addr; phone = Phone; So the right way to do it (in this particular case) is: // Now set the information. Remember, setinfo() is // defined in the Person class astudent.setinfo( Joe Student, 166 Phelps Lane, 555-1212 ); astudent.printinfo(); Demonstration #2 Let s see this in action... Protected Members 3

Cleaning Up our Implementation You might think that the Person class should print its own data: void printinfo(); void Person::printInfo() cout << Name: << name << endl; cout << Addr: << address << endl; cout << Phone: << phone << endl; That makes a certain amount of sense... class Instructor : public Person int employeeid; Cleaning Up our Implementation Instructor aninstructor; aninstructor.setinfo( Ron DiNapoli, 120 Maple Ave, 555-1313 ); aninstructor.printinfo(); Would work just as well (without having to define printinfo() in each derived class) Cleaning Up our Implementation But what about things we might want to print out in a derived class that aren t present in the base class? studentid field in the Student class. employeeid field in the Employee class. Is there any way to include them in the Person::printInfo() member function? Not really, but we can do the next best thing. We could have a special definition of printinfo which is used when we re dealing with a Student class instance cout << Student ID: << studentid << endl; // Hmmmm, how can I call the printinfo() from Person? Cleaning Up our Implementation Wait a minute. If we already have printinfo defined in Person, can we define it Student as well? cout << Student ID: << studentid << endl; // Hmmmm, how can I call the printinfo() from Person? void Person::printInfo() cout << Name: << name << endl; cout << Addr: << address << endl; cout << Phone: << phone << endl; Let s find out... Demonstration #3 Redefining Base Class Member Functions Overriding Yes, it does work. Whenever a derived class defines a member function that is also defined in the base class it is said that the definition in the derived class overrides the definition in the base class. In our previous example, Student::printInfo() overrides Person::printInfo() However, consider the case where we d like to write a function that can take a Person as an argument and will cause that person s printinfo method to be invoked: void printpersoninfo(person &aperson) aperson.printinfo(); 4

Let s consider the following code: Overriding (cont) void printpersoninfo(person &aperson) aperson.printinfo(); Demonstration #4 Instructor aninstructor; astudent.setinfo( Joe Student, 1 E Main St, 555-1212 ); astudent.studentid = 33445; aninstructor.setinfo( Ron D, 120 Maple Ave, 555-1313 ); aninstructor.employeeid = 12345; printpersoninfo(astudent); printpersoninfo(aninstructor); Redefining Base Class Member Functions II Overriding (cont) So, wait a minute. Did the compiler forget that we overrode Person::printInfo() in the derived class Student? No, it s only doing what it was told to do! Recall that we didn t get any complaints from the compiler when we passed aninstructor and astudent in to the function printpersoninfo(person &). It s legal to do that; since Instructor and Student are derived from Person, the compiler thinks we want to treat whatever argument is passed in as a Person. And, since inside the scope of printpersoninfo the argument passed is an instance of a Person, Person::printInfo() is used when we call aperson.printinfo(). Well, doesn t that make overriding somewhat useless? Virtual Functions No, we can achieve the desired behavior by making one minor adjustment to the Person class: virtual void printinfo(); Does this really make a difference? Demonstration #5 Virtual Functions Virtual Functions WOW! What just happened? By defining Person::printInfo() as a virtual function, we told the compiler to keep track of any instances of derived classes which may override this function and make sure the overridden version gets called no matter what type that instance may be cast to. This is usually the desired behavior When a member function is declared as a virtual function, derived classes have the option of overriding it. If they do not, the member function in the base class is always called There s one catch, though In order to get this behavior, we needed to declare the argument to printpersoninfo as a Person & (or Person *). Had we just used Person, a copy of the argument passed would have been used and would have retained no knowledge about actually being a derived class... 5

Demonstration #6 Virtual Functions -- Pass By Value Pure Virtual Functions Suppose the case arose where we wanted to force a derived class to override a specific member function in the base class. Why would we want to do that? Suppose there were a common function implemented across all the derived classes which didn t necessarily make sense to include in the base class. Consider a simple member function which would print out a Person s classification (student, faculty, staff, etc.). Maybe it would look like this void Person::printClassification() cout << This person s classification is <<???? Pure Virtual Functions (cont) The problem here is that the Person class has no idea what classification a person is That is handled in the derived class. So it would be very easy to implement printclassification as a member function of each derived class... void Student::printClassification() cout << Classification: STUDENT << endl; void Instructor::printClassification() cout << Classification: INSTRUCTOR << endl; Now, this will seemingly fit the bill, but there s one problem... Pure Virtual Functions(cont) How can we call it from our printpersoninfo() function? We could add a new member variable to keep track of type... virtual void printinfo(); int PersonType; Then make sure we populate this field in the derived class... Then do something like the following... Pure Virtual Functions (cont) void printpersoninfo(person *aperson) // have to pass pointer aperson->printinfo(); // Now print classification switch( aperson->persontype ) case kstudenttype: // Assume type constants exist Student *astudent = (Student *) aperson; astudent->printclassification(); break; case kinstructortype: Instructor *aninstructor = (Instructor *) aperson; aninstructor->printclassification(); break; Pure Virtual Functions(cont) I don t think so! C++ gives us a way to declare a member function in the base class and specify that every derived class must implement it (because there is no default implementation in the base class) This is called a Pure Virtual Function virtual void printinfo(); virtual void printclassification() = 0; // Pure Virtual 6

Pure Virtual Functions(cont) You declare a member function to be pure virtual by adding a = 0 initializer right after the declaration. After doing this, our printpersoninfo() function becomes simple again... Demonstration #7 void printpersoninfo(person &aperson) aperson.printinfo(); aperson.printclassification(); // Call pure virtual function Let s see this work... Pure Virtual Functions Pure Virtual Functions & Abstract Classes As we just saw, declaring printclassification() as pure virtual caused compiler errors when we tried to work with derived classes which did not define the pure virtual member function. The error messages we received made reference to abstract class An abstract class is simply a base class which contains one or more pure virtual member functions. As such, an instance of an abstract class can never be allocated. You must always declare or allocate an instance of one of its derived classes. This means our printpersoninfo() function must either be passed a reference or pointer to Person. Let s define printclassification() in our derived classes and try again Demonstration #8 Pure Virtual Functions II Final Thoughts Assignment #3 due Thursday This stuff is beginning to get tougher, please visit office hours as needed According to LNG, we have not even started learning C++ yet :-) 7