Part VIII. More classes. Philip Blakely (LSC) C++ Introduction 226 / 370

Similar documents
Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Part X. Advanced C ++

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

step is to see how C++ implements type polymorphism, and this Exploration starts you on that journey.

Part III. Advanced C ++

C++ Inheritance and Encapsulation

Part XI. Algorithms and Templates. Philip Blakely (LSC) C++ Introduction 314 / 370

04-24/26 Discussion Notes

ECE 3574: Dynamic Polymorphism using Inheritance

Compaq Interview Questions And Answers

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

Programming, numerics and optimization

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

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

Written by John Bell for CS 342, Spring 2018

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

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers

What is an algorithm?

CS11 Introduction to C++ Fall Lecture 7

Major Differences between Java and C++ Programming in C++ Multiple Inheritance

Financial computing with C++

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

Instantiation of Template class

IS 0020 Program Design and Software Tools

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to C++ with content from

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

Lecture 5: Inheritance

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

Fast Introduction to Object Oriented Programming and C++

CS304 Object Oriented Programming Final Term

Part V. Memory and pointers. Philip Blakely (LSC) C++ Introduction 145 / 370

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

15: Polymorphism & Virtual Functions

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

COM S 213 Fall 2004 Assignment #4 The Used Car Dealership Expands! Due September 23, 2004

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

eingebetteter Systeme

Virtual functions concepts

C++ Important Questions with Answers

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

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

Increases Program Structure which results in greater reliability. Polymorphism

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

Polymorphism Part 1 1

C++ Programming: Polymorphism

Programming in C and C++

Computer Science II CSci 1200 Lecture 24 C++ Inheritance and Polymorphism

Inheritance STL. Entity Component Systems. Scene Graphs. Event Systems

EL2310 Scientific Programming

OBJECT ORIENTED PROGRAMMING USING C++

(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 Programming. Assistant Lecture Omar Al Khayat 2 nd Year

CPSC 427: Object-Oriented Programming

Advanced C++ Topics. Alexander Warg, 2017

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

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

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

EL2310 Scientific Programming

Java Object Oriented Design. CSC207 Fall 2014

Introduction to C++ Part II. Søren Debois. Department of Theoretical Computer Science IT University of Copenhagen. September 12th, 2005

Implementing Interfaces. Marwan Burelle. July 20, 2012

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

What are the characteristics of Object Oriented programming language?

Programming in C and C++

Comp 249 Programming Methodology Chapter 8 - Polymorphism

Object Oriented Programming. Solved MCQs - Part 2

Short Notes of CS201

CS11 Advanced C++ Fall Lecture 7

Object Oriented Software Design II

Java Fundamentals (II)

Midterm Exam 5 April 20, 2015

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

COMP322 - Introduction to C++

Inheritance: Develop solutions by abstracting real-world object and their interaction into code to develop software solutions. Layering: Organization

Object Oriented Software Design II

CS201 - Introduction to Programming Glossary By

C++ Alexander Baltatzis

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Inheritance and Polymorphism

Framework Fundamentals

C++ Inheritance and Encapsulation

Part XII. More programming comments. Philip Blakely (LSC) C++ Introduction 349 / 370

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Inheritance and Polymorphism

CS

Topic 10. Abstract Classes. I prefer Agassiz in the abstract, rather than in the concrete.

VIRTUAL FUNCTIONS Chapter 10

Financial computing with C++

Exercise: Singleton 1

CS 61B Discussion 5: Inheritance II Fall 2014

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

Copyie Elesion from the C++11 mass. 9 Sep 2016 Pete Williamson

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

Advanced Systems Programming

COP 3530 Discussion Session #2 Ferhat Ay

CS304 Object Oriented Programming

EL2310 Scientific Programming

Transcription:

Part VIII More classes Philip Blakely (LSC) C++ Introduction 226 / 370

Inheritance Outline 29 Inheritance 30 Virtual functions 31 Polymorphism 32 Classes and static Philip Blakely (LSC) C++ Introduction 227 / 370

Inheritance Inheritance In OOP, we may have objects which are of some general type, but are also of some specialised type For example, we may have a Vehicle class with various member functions: Vehicle v; v.setnumberpassengers(4); v.startengine(); However, there are types of vehicle with features not shared by all other vehicles: car.openboot(); doesn t apply to a lorry, for example Philip Blakely (LSC) C++ Introduction 228 / 370

Inheritance Inheritance We would like to have a Car be a specialized type of Vehicle: class Car : public Vehicle { public: void openboot(); }; Now Car inherits the member functions and data of Vehicle, and can be regarded as being of type Vehicle: Car car; car.openboot(); car.startengine(); Vehicle v; v.openboot(); // Compile time error Philip Blakely (LSC) C++ Introduction 229 / 370

Inheritance Protected inheritance for data When Car derives from Vehicle, we may want it to have access to some of Vehicle s data: class Vehicle{ public: void setnumpassengers(int); int getnumpassengers()const; protected: int numpassengers; private: int vehicledata; }; Now, a member-function of Car can access numpassengers, but not vehicledata. Philip Blakely (LSC) C++ Introduction 230 / 370

Inheritance Protected inheritance for functions The same applies to member-functions of a parent class: class Vehicle{ protected: void runstartermotor(); }; This is then not accessible from outside Vehicle (only called through a public function such as turnignitionon). However, it is accessible from member functions of Car because Car inherits Vehicle as a public class Philip Blakely (LSC) C++ Introduction 231 / 370

Inheritance Inheritance rules Suppose we have a classes X and Y: class X{ public: int pub; int m(); protected: int pro; private: int pri; }; class Y : public X { public: int f(); }; int main(){ X x; x.pub=0;// OK x.pro=0;// Error x.pri=0;// Error } int X::m(){ pub = 0;// OK pro = 0;// OK pri = 0;// OK } int Y::f(){ pub = 0;// OK pro = 0;// OK pri = 0;// Error } Philip Blakely (LSC) C++ Introduction 232 / 370

Virtual functions Outline 29 Inheritance 30 Virtual functions 31 Polymorphism 32 Classes and static Philip Blakely (LSC) C++ Introduction 233 / 370

Virtual functions Virtual functions What happens if we want a Car to have a maximum number of passengers, but most Vehicles do not have this restriction? We could introduce a new data-member, maximumpassengers, to the Vehicle class: void Vehicle::setNumberPassengers(int p){ if( p > maximumpassengers){ std::cout << "Crowded" << std::endl; } } However, this represents a leakage of information into the base class Anyway, we would potentially have to do this every time we wanted to add extra information to a Car Philip Blakely (LSC) C++ Introduction 234 / 370

Virtual functions Virtual functions Virtual functions allow definitions of functions in a base-class to be re-implemented by a derived class class Vehicle{ public: virtual void setnumberpassengers(int); }; void Vehicle::setNumberPassengers(int p){ passengers = p; } class Car : public Vehicle{ virtual void setnumberpassengers(int); }; void Car::setNumberPassengers(int p){ if( p > 6 ){ std::cout << "Crowded" << std::endl; } passengers = p; } Philip Blakely (LSC) C++ Introduction 235 / 370

Virtual functions Virtual functions ctd. If setnumberpassengers() is called on a Vehicle, then the first version is called. If setnumberpassengers() is called in a Car, then the second version is called. Lorry l; l.setnumberpassengers(10); // Will not print error message Car c; c.setnumberpassengers(10); // Will print error message Philip Blakely (LSC) C++ Introduction 236 / 370

Virtual functions Abstract classes Consider the function openbonnet: There may be no sensible way of defining the function openbonnet for a generic Vehicle, but all Vehicles must implement this function This can be expressed as follows: class Vehicle{ public: virtual void openbonnet() = 0; }; Philip Blakely (LSC) C++ Introduction 237 / 370

Virtual functions Abstract classes ctd openbonnet is now a pure virtual function Vehicle is an abstract class No object of type Vehicle can now exist All classes derived from Vehicle must implement openbonnet Trying to create an object of type Vehicle will fail. class Car : public Vehicle{ public: virtual void openbonnet(); }; void Car::openBonnet(){... } Vehicle v; // Compile time failure Car c; // OK Vehicle c2 = new Car; // OK c2 >openbonnet(); // Calls Car s version. Philip Blakely (LSC) C++ Introduction 238 / 370

Polymorphism Outline 29 Inheritance 30 Virtual functions 31 Polymorphism 32 Classes and static Philip Blakely (LSC) C++ Introduction 239 / 370

Polymorphism Polymorphism Polymorphism allows objects of one type to be referred to as objects of another type, if their inheritance allows: Vehicle v = new Car; v >setnumberpassengers(4); will call Vehicle s version of setnumberpassengers or Car s, if Car overrides setnumberpassengers as a virtual function Vehicle v[4]; v[0] = new Car; v[1] = new Lorry; v[0] >setnumberpassengers(4); // Calls Car s version v[1] >setnumberpassengers(10); // Calls Lorry s version Philip Blakely (LSC) C++ Introduction 240 / 370

Polymorphism Polymorphism ctd. The function that will be called is only determined at run-time. This does not contradict static type-checking Assigning an object of type Car to a Vehicle pointer causes the compiler to check that Car derives from Vehicle. For a class with virtual functions, the compiler will generate a v-table, which allows it, for a given derived class, to determine which function it should jump to. This could be thought of as a class containing a set of function pointers for each of its virtual functions Calling a virtual function therefore requires a very tiny amount of extra overhead compared to a simple member function call. Philip Blakely (LSC) C++ Introduction 241 / 370

Polymorphism Losing polymorphism (Slicing) Object slicing occurs when a derived object is assigned to a variable of base-class type: DerivedClass d; BaseClass b = d; will compile. However, the assignment only copies data relevant to BaseClass from d to b (the rest has been sliced off). The same problem would occur in the following: DerivedClass d = new DerivedClass; BaseClass b = d; Here, b is only of type BaseClass This behaviour is nearly always undesirable. Philip Blakely (LSC) C++ Introduction 242 / 370

Polymorphism Downcasting So far, we have seen examples of up-casting, where a derived class pointer is converted to a base-class pointer Consider the following: void maintain(vehicle v){ v >checkpedals(); } and we want to call this function for a collection of Vehicles However, only a Bicycle has pedals, so this will fail to compile! (Here, maintain should probably be a member function of Vehicle, but ignore this for the purposes of argument.) How can we check at run-time whether v is a Bicycle? Philip Blakely (LSC) C++ Introduction 243 / 370

Polymorphism Dynamic-casting The following is valid: Bicycle b = dynamic cast<bicycle >(v); and will convert v to be of type Bicycle if possible. If not possible, then the dynamic cast returns NULL: if( b ){ b >checkpedals(); } is perfectly valid. Many uses of dynamic cast are the result of bad design and are better replaced by a member function: bool Vehicle::isBicycle()const; (or just making maintain a virtual member function of Vehicle) However, there are cases where it is needed Philip Blakely (LSC) C++ Introduction 244 / 370

Polymorphism Multiple inheritance It is also possible for a class to derive from multiple classes class EvilWizard : public EvilCreature, public MagicUser{}; since not all EvilCreatures can wield magic, and not all MagicUsers are evil. An EvilWizard can therefore be used as an EvilCreature or as a MagicUser We can now use EvilCreature e = new EvilWizard; if( dynamic cast<magicuser >(e) )... to determine whether an EvilCreature is also a MagicUser. Philip Blakely (LSC) C++ Introduction 245 / 370

Polymorphism Virtual inheritance What happens in the previous example if we have a general Character class? Obviously every EvilCreature is a Character and so is every MagicUser: class MagicUser : public Character{}; class EvilCreature : public Character{}; But now EvilWizard has two Character bases Anything stored in Character will be duplicated, and refering to the Character base of EvilWizard is ambiguous. Philip Blakely (LSC) C++ Introduction 246 / 370

Polymorphism Virtual inheritance We can correct this by using virtual inheritance class MagicUser : public virtual Character{}; class EvilCreature : public virtual Character{}; Now EvilWizard has a unique Character base It can be consistently cast to something of type Character Further, the following is now valid: Character c = new EvilWizard; Philip Blakely (LSC) C++ Introduction 247 / 370

Classes and static Outline 29 Inheritance 30 Virtual functions 31 Polymorphism 32 Classes and static Philip Blakely (LSC) C++ Introduction 248 / 370

Classes and static Static in member functions Recall that static variables are local to a function, but are initialized only once and persist throughout the program s run The same applies to static variables in a class s member-function These are not unique to each class instance: int A::f(int x){ static int firstval = x; return firstval; } A a,b; int x = a.f(5); // x == 5 int y = b.f(6); // y == 5 Philip Blakely (LSC) C++ Introduction 249 / 370

Classes and static Static member data It is permissable to have static member data within a class This data is then available to all instances of the class, similar to global variables, but with class access-permissions Ordinary member data has space allocated when an instance of the class is allocated Static member data must be allocated exactly once per program This is done outside the class definition: class A{ static double mydata; }; double A::myData = 9.80665; For constant static variables of integer or enumeration type only, the initialization can be done inside the class definition: class A{ static const int myval = 9; }; Philip Blakely (LSC) C++ Introduction 250 / 370

Classes and static Static member functions Class member functions may also be static. This means that they do not need a class object on which to be called: class A{ static int f(); }; int A::f(){ return 9; } int x = A::f(); Static member functions may not have const or virtual qualifiers Philip Blakely (LSC) C++ Introduction 251 / 370

Classes and static Use of static One use for static functions is the following: Suppose we have a class which must only be instantiated once in a program We could use a global variable, but this fails to prevent other functions from creating new instances, and means that the initialization of the variable is situated away from the class This is known as a Singleton, and can be implemented as: class MySingleton{ public: static const MySingleton inst(){ static MySingleton s = new MySingleton; return s; } private: MySingleton(); }; Philip Blakely (LSC) C++ Introduction 252 / 370

Classes and static Use of the Singleton Since the constructor is private, this prevents other functions from creating a different instance of MySingleton. Since s is static, only a single instance of MySingleton is created, and this is returned every time inst is called. This construct is used as: const MySingleton sing = MySingleton::inst(); Note that we do not require an object of type MySingleton to call inst. This construct can be used anywhere in the code to reference the unique instance of MySingleton Any misuse of the class, such as multiple instantiations, is prevented. Philip Blakely (LSC) C++ Introduction 253 / 370