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

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

CS Lecture #14

Written by John Bell for CS 342, Spring 2018

Software Design and Analysis for Engineers

Fast Introduction to Object Oriented Programming and C++

Lecture Topics. Administrivia

C++ Inheritance and Encapsulation

377 Student Guide to C++

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

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

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

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

Arrays in C++ Instructor: Andy Abreu

PIC 10A Objects/Classes

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

Increases Program Structure which results in greater reliability. Polymorphism

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

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

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

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

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

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I

Software Design and Analysis for Engineers

Tutorial Corner: Attack of the Clones. Tutorial Corner: Attack of the Clones. Anything but Lutfisk

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

15: Polymorphism & Virtual Functions

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

QUIZ. What is wrong with this code that uses default arguments?

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

CPSC 427: Object-Oriented Programming

QUIZ. Source:

Rules and syntax for inheritance. The boring stuff

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

QUIZ. What are 3 differences between C and C++ const variables?

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

VIRTUAL FUNCTIONS Chapter 10

Lecture Transcript While and Do While Statements in C++

CS24 Week 3 Lecture 1

Introduction to Programming Using Java (98-388)

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

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

Lesson 13 - Vectors Dynamic Data Storage

CSE 333 Final Exam 3/19/14

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

For instance, we can declare an array of five ints like this: int numbers[5];

Pointers and References

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

CS 103 Unit 11. Linked Lists. Mark Redekopp

Darrell Bethea June 6, 2011

Lecture 2, September 4

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

CSE 303: Concepts and Tools for Software Development

CSE 333 Midterm Exam July 24, Name UW ID#

Financial computing with C++

CS 103 Unit 11. Linked Lists. Mark Redekopp

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

CSE 143 Lecture 12 Inheritance

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

CMSC162 Intro to Algorithmic Design II Blaheta. Lab March 2019

CSCI 102 Fall 2010 Exam #1

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Inheritance, and Polymorphism.

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

11. Abstract Classes and Interfaces

Pointers, Arrays and Parameters

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

CSC1322 Object-Oriented Programming Concepts

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

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

QUIZ Friends class Y;

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Lecture 19 CSE August You taught me Language, and my profit on t is I know how to curse. William Shakspere, The Tempest, I, ii.

Introduction to C++ with content from

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

CS 103 Lab - Party Like A Char Star

POLYMORPHISM Polymorphism: the type Polymorphism taking many shapes type of object

Computer Science II CSci 1200 Lecture 18 Operators and Friends

Design Patterns: State, Bridge, Visitor

OOP Fundamental Concepts

Passing arguments to functions by. const member functions const arguments to a function. Function overloading and overriding Templates

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Software Engineering /48

Object Oriented Programming. Solved MCQs - Part 2

Operator overloading

Object-Oriented Programming, Iouliia Skliarova

The Dynamic Typing Interlude

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

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Polymorphism. Arizona State University 1

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer?

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

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Transcription:

Lecture 11 More Inheritance, More Constructors Absolute C++ Chapter 15 Overriding Let s recall the code we were working on from last lecture. We had a base class named Person and two derived classes named Student and Instructor. We defined a method named printinfo() in the base class that prints out generic information, and then overrode that method in the Student class (but did not define it in the Instructor class) We then implemented the following global function: ; Overriding (cont) And tried to call it with the following code ; int main() Student astudent; 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); Overriding (cont) But we didn t see the printinfo() method defined in Student. Did the compiler forget that we overrode Person::printInfo() in the derived class Student? No. 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? No, we can achieve the desired behavior by making one minor adjustment to the Person class: ; Demonstration #1 Does this really make a difference? 1

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... Demonstration #2 (Pass by Value) Pure 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 <<???? ; 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... How can we call it from our printpersoninfo() function? We could add a new member variable to keep track of type... int PersonType; ; Then make sure we populate this field in the derived class... Then do something like the following... 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; ; 2

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 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... ; aperson.printclassification(); // Call pure virtual function Let s see this work... Pure and Abstract Classes Demonstration #3 Pure 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 Constructors--Initialization Shorthand Sometimes it is tedious to write out all of the initializations like we do below: Demonstration #4 int classsize) coursename = thecoursename; instructor = theinstructor; size = classsize; Pure II There is a shorthand we can use to simplify this: 3

Initialization Shorthand (cont) Initialization shorthand: int classsize):coursename(thecoursename), instructor(theinstructor),size(classsize) Any member variable may be initialized in any constructor for the same class in this manner. The format is to append the following expression after the parameter list: : member-name(expression), member-name(expression) Constructors--Quick Summary A default constructor is a constructor which takes no arguments If you declare additional constructors you may need to provide a default constructor which does nothing (if you haven t defined one already) Otherwise you may get Can t construct class errors when trying to create an instance of the class without passing arguments. Other constructors may be added which take arguments This is called constructor overloading. A specific form of function overloading, which we ll discuss a little later The linker will make sure the right one is called, depending on the arguments passed (or lack thereof) A shorthand way to initialize member variables in a Constructor s definition is to follow the parameter list with a colon followed by a comma separated list of member variable names and their initial values in parenthesis. Constructors and Resource Allocation Another common use of constructors is to allocate system resources Memory, GUI objects (Windows, Menus, etc.) Other dynamic structures/classes Consider a modification to the Course class from last lecture which allows us to store a dynamic array of Students as a member variable. class Course Course(); Course(string thecourse,string theinstructor,int classsize); string coursename; string instructor; int size; Student *studentlist; int nextstudent; ; Constructors and Resource Allocation Course::Course() coursename = unknown ; instructor = unknown ; size = nextstudent = 0; studentlist = NULL; int classsize):coursename(thecoursename), instructor(theinstructor),size(classsize), nextstudent(0) studentlist = new Student[size]; It s OK to move the initializations back into the body of the constructor if you re starting to make a mess! Constructors and Inheritance Remember our Person class from earlier? ; We could apply what we ve learned about constructors to do the following: Let s provide a constructor to initialize name,address and phone: Person(string Name,string Addr,string Phone):name(Name), address(addr),phone(phone) ; Oh yeah, constructors can be defined in the class definition too! 4

Oh, wait. Person is an abstract class (has one or more pure virtual functions). That means that we can never create a standalone instance of Person. Hmmm, can we do something with the constructors of the derived classes? Let s look at our Student class again and add a constructor their too... class Student: public Person Student(string Name,string Addr,string Phone,int id); void printinfo(); int getid() return studentid; void printclassification(); int studentid; ; Student::Student(string Name,string Addr,string Phone,int id): name(name),address(addr),phone(phone),studentid(id) Will it work? Nope, it won t work. You can t access the private members of Person, even from the derived class! However, you can call Person s constructor! Student::Student(string Name,string Addr,string Phone,int id): Person(Name,Addr,Phone),studentID(id) Let s verify that this does indeed work... Demonstration #5 Constructors and Inheritance Lecture 11 Final Thoughts 5