Upload
michael-heron
View
72
Download
0
Tags:
Embed Size (px)
DESCRIPTION
This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
Citation preview
INHERITANCEMichael Heron
Introduction• There are three pillars fundamental to the edifice that is
object oriented programming.• Inheritance• Encapsulation• Polymorphism
• It is these three things that turn object orientation from a gimmick into an extremely powerful programming tool.
Inheritance• In this lecture we are going to talk about inheritance and
how it can be applied to C++ programs.• There are several important differences here between Java and C+
+.
• Java and C# are single inheritance languages.• C++ supports multiple inheritance.
• This is much more powerful, but also very difficult to do well.
Inheritance• The concept of inheritance is borrowed from the natural
world.• You get traits from your parents and you pass them on to your
offspring.
• In C++, any class can be the parent of any other object.• The child class gains all of the methods and attributes of the
parent.• This can be modified, more on that later.
Inheritance in the Natural World
Inheritance• Inheritance is a powerful concept for several reasons.
• Ensures consistency of code across multiple different objects.• Allows for code to be collated in one location with the concomitant
impact on maintainability.• Changes in the code rattle through all objects making use of it.
• Supports for code re-use.• Theoretically…
Inheritance• In C++, the most general case of a code system belongs
at the top of the inheritance hierarchy.• It is successively specialised into new and more precise
implementations.• Children specialise their parents• Parents generalise their children.
• Functionality and attributes belong to the most general class in which they are cohesive.
Inheritance• In Java, the concept is simple.
• You create an inheritance relationship by having one class extend another.
• The newly extended class gains all of the attributes and methods of the parent.• It can be used, wholesale, in place of the parent if needed.
• We can also add and specialise attributes and behaviours.• This is the important feature of inheritance.
Inheritance in Javapublic class BankAccount { private int balance;
public void setBalance (int b) { balance=b; }
public int getBalance() { return balance; }}
public class MainClass {
public static void main (String args[]) { BankAccount myAccount; myAccount = new BankAccount(); myAccount.setBalance (100); System.out.println ("Balance is: " + myAccount.getBalance()); }}
Inheritance in Java
public class ExtendedBankAccount extends BankAccount{ private int overdraft;
public boolean adjustBalance (int val) { if (getBalance() - val < 0 - overdraft) { return false; }
setBalance (getBalance() - val); return true; }}
Constructors And Inheritance• When a specialised class is instantiated, it calls the
constructor on the specialised class.• If it doesn’t find a valid one it will error, even if one exists in the
parent.
• Constructors can propagate invocations up the object hierarchy through the use of the super keyword.• super always refers to the parent object in Java.
• Easy to do, because each child has only one parent.
• In a constructor, must always be the first method call.• Everywhere else, it can be anywhere.
Constructors and Inheritancepublic class BankAccount { private int balance;
public BankAccount() { balance = 0; }
public BankAccount (int startBalance) { setBalance (startBalance); }
public void setBalance (int b) { balance=b; }
public int getBalance() { return balance; }}
public class ExtendedBankAccount extends BankAccount{ private int overdraft;
public ExtendedBankAccount (int startBalance) { super (startBalance); }
public ExtendedBankAccount (int startBalance, int startOverdraft) { super (startBalance); overdraft = startOverdraft; }
public boolean adjustBalance (int val) { if (getBalance() - val < 0 - overdraft) { return false; }
setBalance (getBalance() - val); return true; }}
Inheritance in C++• At its basic level, very similar to Java.
• A single colon is used in place of the extends keyword.• We also include public before the class name.
• We’ll talk about why later.
• We have no access to variables and methods defined as private.• More on that in the next lecture.
Inheritance in C++class ExtendedCar : public Car {private: float mpg;public: ExtendedCar(float mpg = 50.0); void set_mpg (float f); float query_mpg();};
ExtendedCar::ExtendedCar (float mpg) : mpg (mpg) {}
float ExtendedCar::query_mpg() { return mpg;}
void ExtendedCar::set_mpg (float f) { mpg = f;}
Constructors in C++• Constructors in specialised C++ classes work in a slightly
different way to in Java.• Constructors cannot set the value in parent classes.
• This syntactically forbidden in C++.
• By default, the matching constructor in the derived class (child class) will be called.• Then the default construtor in the parent will be called.
• From our earlier example, the code will call the matching constructor in ExtendedCar, and then the parameterless constructor in Car.
Constructors in C++• If we want to change that behaviour, we must indicate so
to the constructor.• In our implementation for the constructor, we indicate which of the
constructors in the parent class are to be executed.• We must handle the provision of the values ourselves.
Constructors in C++class ExtendedCar : public Car {private: float mpg;public: ExtendedCar( float cost = 100.0, string colour = "black", int max_size = 10, float mpg = 50.0); void set_mpg (float f); float query_mpg();};
ExtendedCar::ExtendedCar (float cost, string colour, int max_size, float mpg) : Car(cost, colour, max_size), mpg (mpg) {}
Multiple Inheritance• The biggest distinction between C++ and Java inheritance
models is that C++ permits multiple inheritance.• Java and C# do not provide this.
• It must be used extremely carefully.• If you are unsure what you are doing, it is tremendously easy to
make a huge mess of a program.
• It is in fact something best avoided.• Usually.
Multiple Inheritance• We will touch on syntax, rather than discuss it.
• Don’t want to introduce something I don’t want you using!• However, important you understand what is happening when you
see it.
• Inheritance defined in the same way as with a single class.• Separate classes to be inherited with a comma
• Class SuperVehicle: public Car, public Plane
Multiple Inheritance• What are the problems with multiple inheritance?
• Hugely increased program complexity• Problems with ambigious function calls.
• The Diamond Problem
• Hardly ever really needed.• For simple applications, interfaces suffice.
• For more complicated situations, design patterns exist to resolve all the requirements.
• Some languages permit multiple inheritance but resolve some of the technical issues.• C++ isn’t one of them.
Summary• Inheritance is an extremely powerful tool.
• Provides opportunities for code re-use and maintainability.
• Inheritance in C++ is very similar to inheritance in Java.• With some exceptions.
• C++ permits multiple inheritance.• Not something you often need.