Presentation is loading. Please wait.

Presentation is loading. Please wait.

COP 3330 Object-oriented Programming in C++

Similar presentations


Presentation on theme: "COP 3330 Object-oriented Programming in C++"— Presentation transcript:

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

2 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

3 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, ……

4 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)

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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()

13 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()

14 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

15 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

16 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);

17 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!

18 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 ……

19 Code Review Geometric-Object Class

20 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

21 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

22 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

23 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

24 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!

25 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

26 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);

27 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;

28 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;

29 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

30 Questions


Download ppt "COP 3330 Object-oriented Programming in C++"

Similar presentations


Ads by Google