Download presentation
Presentation is loading. Please wait.
Published bySandra Garrett Modified over 6 years ago
1
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design, structure and reusability of code.
2
Encapsulation the bundling of an object’s data and procedures into a single unit. Examples A function encapsulates the details of an algorithm A class encapsulates both variables and functions together in a single unit.
3
Inheritance the capability to derive a new class from an existing class. The initial class used as the basis for the derived class is referred to as either the base, parent or superclass. The derived class is referred to as either the derived, child, or subclass. The derived class inherits all the member variables and functions (except constructors and destructors) of its base class.
4
Inheritance C++ class hierarchy is based upon the principle of increased specialization. The base class carries attributes that are common to all classes and virtual functions that may or may not be overridden. The derived class adds its own additional new data and member functions/methods. A function in the derived class may override a base class function. The derived class inherits the attributes of classes above it in the class hierarchy The specialization can continue over multiple levels
5
Inheritance Protection attributes: Base class member access specifiers
public - Any holder of a pointer to an instance of the class may invoke any public method or modify any public data item. private – methods/data members may be accessed only by methods belonging to the class protected - methods/data members may be access by derived classes but not others
6
class Child : public Parent { }; - protected inheritance
Base Class Access C++ supports three inheritance modes, also called base class access modes: - public inheritance class Child : public Parent { }; - protected inheritance class Child : protected Parent{ }; - private inheritance class Child : private Parent{ };
7
Base Class Access vs. Member Access Specification
Base class access is not the same as member access specification: Base class access: determine access for inherited members Member access specification: determine access for members defined in the class
8
Member Access Specification
Specified using the keywords private, protected, public class MyClass { private: int a; protected: int b; void fun(); public: void fun2(); };
9
Base Class Access Specification
class Child : public Parent { protected: int a; public: Child(); }; base access member access
10
Base Class Access Specifiers
public – object of derived class can be treated as object of base class (not vice-versa) protected – more restrictive than public, but allows derived classes to know some of the details of parents private – prevents objects of derived class from being treated as objects of base class.
11
Inheritance Base class access specifier Type of inheritance public
protected private public in derived class. Can be accessed directly by member functions, friend functions, and nonmember functions. protected in derived class. Can be accessed directly by member functions and friend functions. private in derived class. Can be accessed directly by member functions and friend functions. Can be accessed directly by member functions and friend functions. private in derived class. Can be accessed directly by member functions and friend functions. Hidden in derived class. Can be accessed by member functions and friend functions through public or protected member functions of the base class. Can be accessed by member functions and friend functions through public or protected member functions of the base class. Can be accessed by member functions and friend functions through public or protected member functions of the base class.
12
Order of Execution When an object of a derived class is created, the base class’s constructor is executed first, followed by the derived class’s constructor When an object of a derived class is destroyed, its destructor is called first, then that of the base class See pr11-20.cpp
13
Order of Execution int main() { UnderGrad u1; ... return 0;
// Student – base class // UnderGrad – derived class // Both have constructors, destructors int main() { UnderGrad u1; ... return 0; }// end main Execute Student constructor, then execute UnderGrad constructor Execute UnderGrad destructor, then execute Student destructor
14
Passing Arguments to Base Class Constructor
Allows selection between multiple base class constructors Specify arguments to base constructor on derived constructor heading Can also be done with inline constructors Must be done if base class has no default constructor
15
Passing Arguments to Base Class Constructor
class Parent { public: Parent(int,int); private: int x, y; }; class Child : public Parent { Child(int a): Parent(a,a*a){ z = a; } int z; See inheritance2.h, inheritance2.cpp, pr11-21App.cpp
16
Overriding Base Class Functions
Overriding function: function in a derived class that has the same name and parameter list as a function in the base class Typically used to replace a function in base class with different actions in derived class Not the same as overloading – with overloading, the parameter lists must be different See inheritance3.h, inheritance3.cpp, pr11-21.cpp
17
Access to Overridden Function
When a function is overridden, all objects of derived class use the overriding function. If necessary to access the overridden version of the function, it can be done using the scope resolution operator with the name of the base class and the name of the function: Student::getName(); See inheritance4.h, inheritance4.cpp, and Pr11-22App.cpp
18
Type Compatibility in Inheritance Hierarchies
Classes in a program may be part of an inheritance hierarchy Classes lower in the hierarchy are special cases of those above Vehicle Car Truck 18-Wheeler
19
Type Compatibility in Inheritance
A pointer to a derived class can be assigned to a pointer to a base class. Another way to say this is: A base class pointer can point to derived class objects Vehicle *vehPtr = new Car;
20
Type Compatibility in Inheritance
Assigning a base class pointer to a derived class pointer requires a cast Vehicle *carPtr = new Car; Car *carPtr; carPtr = static_cast<Car *>(vehPtr); The base class pointer must already point to a derived class object for this to work See inheritance4.h and pr15-01.cpp
21
Using Type Casts with Base Class Pointers
C++ uses the declared type of a pointer to determine access to the members of the pointed-to object If an object of a derived class is pointed to by a base class pointer, all members of the derived class may not be accessible Type cast the base class pointer to the derived class (via static_cast) in order to access members that are specific to the derived class
22
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually pointed to Static binding is done at compile time
23
Late Binding / Dynamic Binding
technique of waiting until runtime to determine which version of a member function is appropriate Can look at the actual class of the object pointed to and choose the most specific version of the function Dynamic binding is used to bind virtual functions Polymorphism is another word for late binding.
24
Polymorphism Enables us to write programs that process objects of classes that are part of the same class hierarchy as if they were all objects of the hierarchy’s base class.
25
Virtual Functions (C++ only)
By default, C++ matches a function call with the correct function definition at compile time -- static binding. Can specify that the compiler match a function call with the correct function definition at run time -- dynamic binding. Declare a function with the keyword virtual if you want the compiler to use dynamic binding for that specific function.
26
Virtual Functions (C++ only)
The virtual function specification tells the compiler to create a pointer to a function f(), but to not fill in the value of the pointer until the function is actually called. Declaring a function virtual will make the compiler check the type of each object to see if it defines a more specific version of the virtual function;
27
Virtual Functions (C++ only)
the compiler chooses the appropriate definition of f(), not by the type of reference, but by the type of object that the reference refers to. Therefore, a virtual function is a member function you may redefine for other derived classes, and can ensure that the compiler will call the redefined virtual function for an object of the corresponding derived class, even if you call that function with a pointer or reference to a base class of the object.
28
Virtual Functions (C++ only)
To create a virtual function, place the keyword virtual before the function's return type in the declaration section. Once a function is declared as virtual, it remains virtual for the next derived class with or without a virtual declaration in the derived class. The virtual declaration in the derived class is not needed, but is usually included both for clarity and to ensure that any subsequently derived classes correctly inherit the function.
29
Virtual Functions (C++ only)
A class that declares or inherits a virtual function is called a polymorphic class. You redefine a virtual member function, like any member function, in any derived class.
30
Polymorphism and Virtual Member Functions
Polymorphic code: Code that behaves differently when it acts on objects of different types Virtual Member Function: The C++ mechanism for achieving polymorphism
31
Polymorphism Consider the Vehicle, Car, Truck hierarchy where each class has its own version of the member function printType( ) Vehicle Car Truck 18-Wheeler
32
Polymorphism class Vehicle { public: Vehicle(); Vehicle(…); void printType(); private: string type; ;
33
Polymorphism class Car : public Vehicle { public: Car(); Car(…) void printType(); … }
34
Polymorphism class Truck : public Vehicle { public: Truck(); Truck(…) void printType(); … }
35
Polymorphism void Vehicle::printType() { cout << "vehicle"; }
36
Polymorphism void Car::printType() { cout << "car"; }
37
Polymorphism void Truck::printType() { cout << "truck"; }
38
Polymorphism Consider the collection of different Vehicle objects
Vehicle *vehCollection[] = {new Vehicle, new Car,new Truck}; and accompanying code for(int k=0; k<3; k++) vehCollection[k]->printType(); Prints: vehicle vehicle vehicle ignoring the more specific versions of printType() in Car and Truck See inheritance4.h and pr15-02.cpp
39
Polymorphism The preceding code is not polymorphic: it behaves the same way even though Vehicle, Car, and Truck have different types and different printType() member functions. Static binding is used. In the expression vehCollection[k]->printType(); the compiler sees only the type of the pointer vehCollection[k], which is pointer to Vehicle; it does not see the type of the actual object pointed to, which may be Vehicle, or Car, or Truck
40
Polymorphism Polymorphic code would have printed vehicle car truck
instead of vehicle vehicle vehicle
41
Virtual Functions If the member functions printType()are declared virtual, then the code Vehicle *vehCollection[] = {new Vehicle, new Car,new Truck}; for(int k=0; k<3; k++) vehCollection[k]->id(); will print vehicle car truck See inheritance5.h and pr15-03.cpp
42
Virtual Functions Declaring printType() as a virtual function class Vehicle { public: … virtual void printType(); }
43
Virtual Functions Declaring printType() as a virtual function: class Car : public Vehicle { … virtual void printType(); }
44
Virtual Functions Declaring printType() as a virtual function: class Truck : public Vehicle { … virtual void printType(); }
45
Virtual functions Now that printType() is declared virtual,
vehCollection[k]->printType() will print vehicle car truck dynamic binding is used and the compiler chooses the appropriate definition of printType() by the type of object that the reference refers to.
46
Polymorphism The code is not polymorphic because in the expression
vehCollection[k]->printType(); the compiler sees only the type of the pointer vehCollection[k], which is pointer to Vehicle Static binding is used.
47
Abstract Base Classes and Pure Virtual Functions
An abstract class is a class that contains no objects that are not members of subclasses (derived classes) For example, in real life, Animal is an abstract class: there are no animals that are not dogs, or cats, or lions…
48
Abstract Base Classes and Pure Virtual Functions
Abstract classes are an organizational tool. They are useful in organizing inheritance hierarchies Abstract classes can be used to specify an interface that must be implemented by all subclasses
49
Abstract Functions The member functions specified in an abstract class do not have to be implemented The implementation is left to the subclasses In C++, an abstract class is a class with at least one abstract member function
50
Pure Virtual Functions
In C++, a member function of a class is declared to be an abstract function by making it virtual and replacing its body with = 0; class Animal{ public: virtual void id()=0; }; A virtual function with its body omitted and replaced with =0 is called a pure virtual function, or an abstract function See pr15-04.cpp
51
Abstract Classes An abstract class can not be instantiated
An abstract class can only be inherited from; that is, you can derive classes from it Classes derived from abstract classes must override all pure virtual functions with concrete member functions before they can be instantiated.
52
Composition vs. Inheritance
Inheritance models an 'is a' relation between classes. An object of a derived class 'is a(n)' object of the base class Example: an UnderGrad is a Student a Mammal is an Animal a Poodle is a Dog
53
Composition vs. Inheritance
When defining a new class: Composition is appropriate when the new class needs to use an object of an existing class Inheritance is appropriate when objects of the new class are a subset of the objects of the existing class, or objects of the new class will be used in the same ways as the objects of the existing class See pr15-05.cpp
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.