Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 15: Polymorphism,
ITEC200 – Week03 Inheritance and Class Hierarchies.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 11 More.
Inheritance, Polymorphism, and Virtual Functions
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation - a language mechanism for restricting access to some.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using work from: Starting Out with C++ Early Objects Eighth Edition.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Object Oriented Programming
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter -6 Polymorphism
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley What Is Inheritance? 15.1.
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
A First Book of C++ Chapter 12 Extending Your Classes.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Polymorphism in Methods
Modern Programming Tools And Techniques-I
7. Inheritance and Polymorphism
Inheritance and Polymorphism
Class A { public : Int x; A()
Object-Oriented Programming
Inheritance, Polymorphism, and Virtual Functions
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Types of Programming Languages
Advanced C++ Topics Chapter 8.
Inheritance Basics Programming with Inheritance
Inheritance Using work from:
Learning Objectives Inheritance Virtual Function.
Java Programming Language
Inheritance, Polymorphism, and Virtual Functions
Polymorphism Polymorphism
Computer Programming with JAVA
Java – Inheritance.
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Object-Oriented Programming: Inheritance and Polymorphism
Fundaments of Game Design
Chapter 9 Carrano Chapter 10 Small Java
Chapter 8: Class Relationships
Overview of C++ Polymorphism
CIS 199 Final Review.
Jim Fawcett CSE687 – Object Oriented Design Spring 2014
C++ Object Oriented 1.
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.
Computer Science II for Majors
Presentation transcript:

Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design, structure and reusability of code.

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.

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.

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

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

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{ };

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

Member Access Specification Specified using the keywords private, protected, public class MyClass { private: int a; protected: int b; void fun(); public: void fun2(); };

Base Class Access Specification class Child : public Parent { protected: int a; public: Child(); }; base access member access

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.

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.

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

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

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

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

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

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

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

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;

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

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

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

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.

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.

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.

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;

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.

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.

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.

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

Polymorphism Consider the Vehicle, Car, Truck hierarchy where each class has its own version of the member function printType( ) Vehicle Car Truck 18-Wheeler

Polymorphism class Vehicle { public: Vehicle(); Vehicle(…); void printType(); private: string type; ;

Polymorphism class Car : public Vehicle { public: Car(); Car(…) void printType(); … }

Polymorphism class Truck : public Vehicle { public: Truck(); Truck(…) void printType(); … }

Polymorphism void Vehicle::printType() { cout << "vehicle"; }

Polymorphism void Car::printType() { cout << "car"; }

Polymorphism void Truck::printType() { cout << "truck"; }

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

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

Polymorphism Polymorphic code would have printed vehicle car truck instead of vehicle vehicle vehicle

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

Virtual Functions Declaring printType() as a virtual function class Vehicle { public: … virtual void printType(); }

Virtual Functions Declaring printType() as a virtual function: class Car : public Vehicle { … virtual void printType(); }

Virtual Functions Declaring printType() as a virtual function: class Truck : public Vehicle { … virtual void printType(); }

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.

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.

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…

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

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

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

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.

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

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