Inheritance
Michael Heron
Introduction
• Last week we discussed object orientation a little bit.
• Introducing one of the key principles of object orientation –
encapsulation.
• This week we will round off our discussion of object
orientation.
• Today we talk about the principle of inheritance.
• Tomorrow we’re going to discuss general object design.
Encapsulation Revisited
• One of the things that makes encapsulation a powerful tool is
that we have one distinct unit to represent a collection of data
and methods.
• We can leverage this representation in various ways.
• It is the foundation of several other object oriented principles.
• One of the things that extend from this system is the principle
of inheritance.
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 C++
• At its basic level, relatively simple.
• A single colon is used in place of the extends keyword.
• We also include public before the class name.
• We have no access to variables and methods defined as
private.
• This is where the visibility modifiers we discussed last week come
into play.
Inheritance in C++
class Car {
private:
float price;
public:
void set_price (float p);
float query_price();
};
This is the header file for our class – remember classes in C++ are spread over two
files. The header file defines the class structure, and includes none of the code.
Inheritance in C++
#include "car.h”
void Car::set_price (float p) {
price = p;
}
float Car::query_price() {
return price;
}
This is the cpp file for the class – it defines the code, but doesn’t define what the class
structure is. That’s left for the header file.
Inheritance in C++
class ExtendedCar : public Car {
private:
float mpg;
public:
void set_mpg (float f);
float query_mpg();
};
float ExtendedCar::query_mpg() {
return mpg;
}
void ExtendedCar::set_mpg (float f) {
mpg = f;
}
Constructors
• It is often useful for us to be able to setup an object with
some starting values to its attributes.
• We can do this using a constructor method.
• This is a special method called whenever an object is created.
• Constructor methods work the same way as other methods.
• They just have a slightly different format.
Constructors in Theory
• It is called automatically when an object is initialized.
• When we create an object from a class.
• Can be used for any purpose, but most often used for
initializing data fields.
• We can provide a range of constructor methods inside an
object to deal with all eventualities.
Constructors
• Constructors must have the same name as the class in which
they are defined.
• Constructors have no return type.
• They are not void, the return type is actually omitted.
• They are usually declared as public.
• A well designed object will often provide several constructors.
• This is perfectly valid, provided they all have unique method
signatures.
Constructors in C++
• These are declared in the same way as any method, in the
header file:
class Car {
private:
float price;
public:
Car();
void set_price (float p);
float query_price();
};
Constructors in C++
• Data fields in a C++ constructor are initialised like so:
Car::Car() :
price (200.0),
colour ("black") {
}
C++ Constructor Code
Note that the method here has no return type – this distinguishes it from other
kinds of methods in C++.
Constructors in C++
• Initialization lists may look like function calls.
• They’re not.
• The name of the entries in the list refer specifically to the name
of attributes only.
• You can make use of parameters passed to constructors in the
initialization lists also.
Car::Car(float p) :
price (p) {
}
Rules of Constructors
• If no constructors are defined by the developer, a default case
is provided.
• This is a zero parameter constructor with no attached
functionality.
• If any developer-defined constructor exists, the compiler will
not provide one.
• Even if the defined constructor has parameters.
• You should always provide a zero parameter constructor.
• We won’t talk about why – it’s just Good Practice.
Constructors
• The constructor method gets called whenever an object is
created.
• The compiler figures out which constructor should be called
by examining the parameter list.
• Only one of the constructors will be called.
• As far as C++ is concerned, they are all different methods even if
they share a name.
Default Parameters
• C++ Constructors (and methods) allow for default values to be
specified for parameters.
• This is a feature not available in Java.
• Default values are specified in the declaration only.
• Parameters with default values must come at the end of the
parameter list.
Declaring And Using A Default
Parameter
Declaration
Car (float, string = "bright green");
Using
int main() {
Car my_car (500.0);
cout << my_car.query_price() << endl;
return 1;
}
Why Use A Constructor?
• Constructors allow for the developer to ensure a minimum
level of data is contained within an object.
• Avoids the need to hard-code validation into data algorithms.
• You can assume that the objects you are working with will be
configured in some syntactically correct way.
Why Use A Constructor?
• In large multi-developer projects, while you can often assume
good faith, you cannot rely on it.
• You can provide documentation to say that every instantiation of
an object should be followed by calls to accessors. You can’t
ensure people follow it.
• Constructor methods allow you to enforce at compilation the
correctness of object configuration.
• The earlier in the development process errors are encountered,
the easier they are to fix.
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,
float mpg = 50.0);
void set_mpg (float f);
float query_mpg();
};
ExtendedCar::ExtendedCar (float cost, float mpg)
: Car(cost),
mpg (mpg) {
}
Summary
• Inheritance is a powerful tool for reusability in C++.
• We only touch on it in this module – no need to worry too much
about it.
• Constructor methods in a C++ program permit us to have
control over the starting values of data fields in our objects.
• Important and useful.

CPP15 - Inheritance

  • 1.
  • 2.
    Introduction • Last weekwe discussed object orientation a little bit. • Introducing one of the key principles of object orientation – encapsulation. • This week we will round off our discussion of object orientation. • Today we talk about the principle of inheritance. • Tomorrow we’re going to discuss general object design.
  • 3.
    Encapsulation Revisited • Oneof the things that makes encapsulation a powerful tool is that we have one distinct unit to represent a collection of data and methods. • We can leverage this representation in various ways. • It is the foundation of several other object oriented principles. • One of the things that extend from this system is the principle of inheritance.
  • 4.
    Inheritance • The conceptof 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.
  • 5.
    Inheritance in theNatural World
  • 6.
    Inheritance • Inheritance isa 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…
  • 7.
    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.
  • 8.
    Inheritance in C++ •At its basic level, relatively simple. • A single colon is used in place of the extends keyword. • We also include public before the class name. • We have no access to variables and methods defined as private. • This is where the visibility modifiers we discussed last week come into play.
  • 9.
    Inheritance in C++ classCar { private: float price; public: void set_price (float p); float query_price(); }; This is the header file for our class – remember classes in C++ are spread over two files. The header file defines the class structure, and includes none of the code.
  • 10.
    Inheritance in C++ #include"car.h” void Car::set_price (float p) { price = p; } float Car::query_price() { return price; } This is the cpp file for the class – it defines the code, but doesn’t define what the class structure is. That’s left for the header file.
  • 11.
    Inheritance in C++ classExtendedCar : public Car { private: float mpg; public: void set_mpg (float f); float query_mpg(); }; float ExtendedCar::query_mpg() { return mpg; } void ExtendedCar::set_mpg (float f) { mpg = f; }
  • 12.
    Constructors • It isoften useful for us to be able to setup an object with some starting values to its attributes. • We can do this using a constructor method. • This is a special method called whenever an object is created. • Constructor methods work the same way as other methods. • They just have a slightly different format.
  • 13.
    Constructors in Theory •It is called automatically when an object is initialized. • When we create an object from a class. • Can be used for any purpose, but most often used for initializing data fields. • We can provide a range of constructor methods inside an object to deal with all eventualities.
  • 14.
    Constructors • Constructors musthave the same name as the class in which they are defined. • Constructors have no return type. • They are not void, the return type is actually omitted. • They are usually declared as public. • A well designed object will often provide several constructors. • This is perfectly valid, provided they all have unique method signatures.
  • 15.
    Constructors in C++ •These are declared in the same way as any method, in the header file: class Car { private: float price; public: Car(); void set_price (float p); float query_price(); };
  • 16.
    Constructors in C++ •Data fields in a C++ constructor are initialised like so: Car::Car() : price (200.0), colour ("black") { } C++ Constructor Code Note that the method here has no return type – this distinguishes it from other kinds of methods in C++.
  • 17.
    Constructors in C++ •Initialization lists may look like function calls. • They’re not. • The name of the entries in the list refer specifically to the name of attributes only. • You can make use of parameters passed to constructors in the initialization lists also. Car::Car(float p) : price (p) { }
  • 18.
    Rules of Constructors •If no constructors are defined by the developer, a default case is provided. • This is a zero parameter constructor with no attached functionality. • If any developer-defined constructor exists, the compiler will not provide one. • Even if the defined constructor has parameters. • You should always provide a zero parameter constructor. • We won’t talk about why – it’s just Good Practice.
  • 19.
    Constructors • The constructormethod gets called whenever an object is created. • The compiler figures out which constructor should be called by examining the parameter list. • Only one of the constructors will be called. • As far as C++ is concerned, they are all different methods even if they share a name.
  • 20.
    Default Parameters • C++Constructors (and methods) allow for default values to be specified for parameters. • This is a feature not available in Java. • Default values are specified in the declaration only. • Parameters with default values must come at the end of the parameter list.
  • 21.
    Declaring And UsingA Default Parameter Declaration Car (float, string = "bright green"); Using int main() { Car my_car (500.0); cout << my_car.query_price() << endl; return 1; }
  • 22.
    Why Use AConstructor? • Constructors allow for the developer to ensure a minimum level of data is contained within an object. • Avoids the need to hard-code validation into data algorithms. • You can assume that the objects you are working with will be configured in some syntactically correct way.
  • 23.
    Why Use AConstructor? • In large multi-developer projects, while you can often assume good faith, you cannot rely on it. • You can provide documentation to say that every instantiation of an object should be followed by calls to accessors. You can’t ensure people follow it. • Constructor methods allow you to enforce at compilation the correctness of object configuration. • The earlier in the development process errors are encountered, the easier they are to fix.
  • 24.
    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.
  • 25.
    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.
  • 26.
    Constructors in C++ classExtendedCar : public Car { private: float mpg; public: ExtendedCar( float cost = 100.0, float mpg = 50.0); void set_mpg (float f); float query_mpg(); }; ExtendedCar::ExtendedCar (float cost, float mpg) : Car(cost), mpg (mpg) { }
  • 27.
    Summary • Inheritance isa powerful tool for reusability in C++. • We only touch on it in this module – no need to worry too much about it. • Constructor methods in a C++ program permit us to have control over the starting values of data fields in our objects. • Important and useful.