COP 3330 Object-oriented Programming in C++

Slides:



Advertisements
Similar presentations
LOGO Lecturer: Abdullahi Salad Abdi May 1, Object Oriented Programming in C++
Advertisements

CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
You gotta be cool. Inheritance Base Classes and Derived Classes Inheritance: Public, Protected, Private What is inherited from the base class? Multiple.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Polymorphism CS351 – Programming Paradigms.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Object Oriented Programming: Inheritance Chapter 9.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 12: Adding Functionality to Your Classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 Inheritance Chapter 9. 2 What You Will Learn Software reusability (Recycling) Inheriting data members and functions from previously defined classes.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Object Oriented Programming COP3330 / CGS5409.  Inheritance  Assignment 5.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
CS1201: Programming Language 2 Classes and objects Inheritance Nouf Aljaffan Edited by : Nouf Almunyif.
Object Oriented Programming: Inheritance Chapter 9.
Design issues for Object-Oriented Languages
The Object-Oriented Thought Process Chapter 03
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Object Oriented Programming: Inheritance
Modern Programming Tools And Techniques-I
Object-Oriented Programming: Inheritance
Inheritance CMSC 202, Version 4/02.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Andy Wang Object Oriented Programming in C++ COP 3330
Inheritance and Polymorphism
Inheritance Basics Fall 2008
Object-Oriented Programming
Review: Two Programming Paradigms
Inheritance in Java.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Week 4 Object-Oriented Programming (1): Inheritance
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 14 Inheritance Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Andy Wang Object Oriented Programming in C++ COP 3330
CS1201: Programming Language 2
Java Programming Language
MSIS 670 Object-Oriented Software Engineering
Lecture 22 Inheritance Richard Gesick.
Inheritance Dr. Bhargavi Goswami Department of Computer Science
Inheritance, Polymorphism, and Virtual Functions
Advanced Programming Behnam Hatami Fall 2017.
Object Oriented Programming: Inheritance
More Object-Oriented Programming
Dr. Bhargavi Dept of CS CHRIST
Polymorphism Polymorphism
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Programming with ANSI C ++
C++ Inheritance.
Fundaments of Game Design
Java Programming Language
CPS120: Introduction to Computer Science
COP 3330 Object-oriented Programming in C++
Jim Fawcett CSE687 – Object Oriented Design Spring 2014
Inheritance in C++ Inheritance Protected Section
C++ Object Oriented 1.
SPL – PS3 C++ Classes.
Programming in C# CHAPTER 5 & 6
Presentation transcript:

COP 3330 Object-oriented Programming in C++ Inheritance Spring 2019

Hierarchical Relationships of Classes Many types of classes share similarities in information and behavior Similar private member data Similar member functions Inheritance Factoring out common features into a single base class Build derived classes that will share or inherit all of the data and functionality of the base class Except constructors, destructors, and assignment operators

Examples Base Class Derived Classes Geometric Objects Circles, Squares, Diamonds, …… Sports Football, Baseball, Basketball, …… Bank Accounts Checking, Savings, Mortgage, …… Vehicles Cars, Trains, Buses, …… Cars Sedan, Coupe, SUV, ……

Inheritance vs. Composition Inheritance: The base class/derived class relationship is an “is-a” relationship Derived object is an instance of the base object Usually a subcategory Composition: “has-a” relationship An object of one class is a component of another class (i.e., is embedded in another object)

Declaring Derived Classes Format class derivedClassName : public baseClassName The base class must be declared somewhere in that file or another, included file public in the derivation syntax: The derived class is publicly derived from the base class The protection levels in the derived class are the same as in the base class It is also possible to derive using other protection levels

Examples class Sport {…}; class Football : public Sport {…}; class Baseball : public Sport {…}; class BankAccount {…}; class Checking : public BankAccount {…}; class Vehicle {…}; class Car : public Vehicle {…}; class SUV : public Car {…}; Car inherits everything in the Vehicle class SUV inherits everything in the Car class Thus, SUV inherits everything from the Vehicle class

Revisit: Protection Levels in Classes Public (member data and functions) Can be accessed by name from anywhere Private Can be accessed directly only by the class in which it is declared We would like derived classes to have access to the members inherited from the base class, but we still want protection from outside access Solution: Protected Can be accessed directly by the class in which it is declared and by ANY classes derived from that class – but not from anywhere else

Types of Inheritance When deriving a class from a base class, the base class may be inherited through public, protected, or private inheritance Syntax: class derivedClassName : public baseClassName class derivedClassName : private baseClassName class derivedClassName : protected baseClassName We hardly use protected or private inheritance, but public inheritance is commonly used

Types of Inheritance Public inheritance - protection levels stay the same in derived class (besides private) public members of the base class become public members of the derived class protected members of the base class become protected members of the derived class. A base class's private members are NEVER accessible directly from a derived class, but can be accessed through calls to functions of the base class Protected inheritance  public and protected members of the base class become protected members of the derived class. Private inheritance  public and protected members of the base class become private members of the derived class

derivedFromProtectedDerived Types of Inheritance If we derive a class  derivedFromProtectedDerived from protectedDerived, x and y are also inherited to the derived class If we derive a class  derivedFromPrivateDerived  from privateDerived, x and y are NOT inherited because they are private variables of privateDerived

Constructors in Derived Classes We know that when an object is created, its constructor runs  However, what happens when a derived object is created? A derived object “is an” instance of the base class Thus, when a derived object is created, the constructors from BOTH the base and derived classes will run The base class will run first, then the derived

Example Vehicle obj1; Only the Vehicle() constructor runs Car obj2; //Car inherits from Vehicle Vehicle() constructor runs, followed by the Car() constructor SUV obj3; //SUV inherits from Car Vehicle() Car() SUV()

Destructors Destructors will be invoked in the reverse order, first the children, then the base classes Example: SUV obj3; //SUV inherits from Car //Car inherits from Vehicle Order of destructors: ~SUV() ~Car() ~Vehicle()

Constructors with Parameters Without parameters, the default constructors are called Example: with a derived class, we might want to declare SUV s(2, 3, 4, “green”, “Honda Pilot”); 2 and 3 might be for variables like vehicleCategory and idNumber in the Vehicle Class 4 and “green” might be for variables like numDoors and carColor in the Car Class “Honda Pilot” might be for a variable model in the SUV class

How to Distribute Paramters? Use an initialization list function prototype : initialization list { function body; } Use the initialization list to call the next higher constructor explicitly, in order to send the parameters to the parent constructor An initialization list is run before the function body actually runs

Example Vehicle::Vehicle(int c, int id) { vehicleCategory = c; idNumber = id; } Car::Car(int c, int id, int nd, char *cc) : Vehicle(c, id) numDoors = nd; strcpy(carColor, cc); SUV::SUV(int c, int id, int nd, char *cc, char *mod) : Car(c, id, nd, cc) strcpy(model, mod);

Function Overriding Suppose we have the following base class class Student { public: void gradeReport(); …… }; We also have the following derived classes, which inherit everything from Student class Grad : public Student class Undergrad : public Student Suppose gradeReport look different for undergrads and grads These classes need to have their own implementations But using the exact same prototype!

Function Overidding class Grad : public Student { public: void gradeReport(); … }; class Undergrad : public Student void Student::gradeReport() { // processing done by parent function } void Grade::gradeReport() { // explicit call to parent function Student::gradeReport(); // other processing specific to Grad’s version ……

Code Review Geometric-Object Class

Multiple Inheritance C++ supports multiple inheritance A class can inherit properties from more than one base class (a class can inherit from multiple parent classes) Not all object-oriented languages support multiple inheritance (e.g., Java) It is not a necessary feature of object-oriented programming Can introduce issues that make maintenance of programs hard

Constructors/Destructors for Multi-Inheritance The constructors of base classes are always called in the same order in which they are inherited B’s constructor is called before A’s constructor Destructors are called in reverse order: A’s destructor will be called before B’s destructor

Ambiguity in Multiple Inheritance While multiple inheritance seems like a simple extension of single inheritance, it can introduce issues and make maintenance hard Ambiguity Arises when multiple base classes contain a function with the same name Compiler does not know which version to call unless we explicitly specify it by using derivedObject.BaseClass::function() While this workaround is simple, things can get complex when your class inherits from many base classes, which inherit from other classes themselves

The Diamond Problem Occurs when a class inherits from two classes each of which inherits from a single base class. This leads to a diamond shaped inheritance pattern

The Diamond Problem There are many issues that arise in this context Whether Copier should have one or two copies of PoweredDevice? How to resolve certain types of ambiguous references? While most of these issues can be addressed through explicit scoping, the maintenance overhead added to your classes in order to deal with the added complexity can cause development time to skyrocket!

The Diamond Problem C++ by default follows each inheritance path separately, so a Copier object would actually contain two sub-objects (two copies) of PoweredDevice’s member variables and functions: one from Scanner one from Printer Uses of PoweredDevice's members would have to be properly qualified and references specified

The Diamond Problem To disambiguate: Copier b; PoweredDevice &a = b; /* error: which PoweredDevice subobject should a Copier be cast to? a Scanner::PoweredDevice or a Printer::PoweredDevice? */ To disambiguate: PoweredDevice &scanner = static_cast<Scanner&> (b); PoweredDevice &printer = static_cast<Printer&> (b);

The Diamond Problem If PoweredDevice would have a function void do() and a member data int var To disambiguate: The same disambiguation, or explicit qualification is needed:  Copier c; c.Scanner::do(); c.Printer::do(); c.Scanner::var = 0; c.Printer::var = 0;

Virtual Inheritance Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes class B: virtual public A class PoweredDevice {}; class Scanner: virtual public PoweredDevice{}; class Printer: virtual public PoweredDevice{}; class Copier: public Scanner, public Printer;

Is multiple inheritance more trouble than it’s worth? Most of the problems that can be solved by multiple inheritance can be solved by single inheritance as well Many object-oriented languages do not even support multiple inheritance Many experienced programmers believe multiple inheritance in C++ should be avoided at all costs due to the many potential problems it brings  If there are times and situations when multiple inheritance is the best way to proceed, use it extremely cautiously

Questions