0% found this document useful (0 votes)
52 views

Chapter 11 Inheritance

This document discusses inheritance and composition in C++ programming. It covers objectives like learning about inheritance, derived and base classes, redefining member functions, constructors and destructors of base and derived classes. It provides examples of inheritance relationships between classes like shape and rectangle/circle. It also discusses public, protected and private inheritance, and composition. Key concepts covered are inheritance for code reuse, derived classes inheriting from base classes, overriding base class functions in derived classes, and relationships between base and derived class constructors and destructors.

Uploaded by

Raksa Ma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Chapter 11 Inheritance

This document discusses inheritance and composition in C++ programming. It covers objectives like learning about inheritance, derived and base classes, redefining member functions, constructors and destructors of base and derived classes. It provides examples of inheritance relationships between classes like shape and rectangle/circle. It also discusses public, protected and private inheritance, and composition. Key concepts covered are inheritance for code reuse, derived classes inheriting from base classes, overriding base class functions in derived classes, and relationships between base and derived class constructors and destructors.

Uploaded by

Raksa Ma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

INHERITANCE &

COMPOSITION

Chapter 11
C++ Programming
OBJECTIVES:
 Learn about Inheritance
 Learn about derived and base classes
 Explore how to redefine the member functions of a base class
 Examine how the constructors of base and derived classes work
 Learn how the destructors of base and derived classes work
 Learn how the construct the header file of a derived class
 Become aware of stream classes hierarchy
 Explore three types of inheritance public, protected, and private
 Learn about composition (aggregation)
 Become familiar with the three basic principles of object-oriented design.
INHERITANCE
 This important feature encourages code reuse.
 Relate two or more classes in more than one way.
 Two common ways to relate classes in a meaningful way are:
 Inheritance (“is-a” relationship) ex: rectangle IS A shape.
 Composition (aggregation) (“has-a” relationship)
OOP – INHERITANCE – (CLASS & SUBCLASSES)

 Inheritance: The ability to create new objects


(classes) from existing objects (classes).
 One of the most powerful features of C++ is the
use of derived classes/Inheritance. Inheritance
Class derived from another Class.
INHERITANCE AND DERIVED CLASSES
 The base class (shape) has two derived classes (rectangle, circle).
 Treelink, hierarchical, structure wherein a base class is shown with its
derived classes.
INHERITANCE AND DERIVED CLASSES

 memberAccessSpecifier is public, protected, or private.


 When if it’s not specified?
INHERITANCE
Facts about the base and the derived classes:
1. The private members of a base class remain private to the base
class.
derived class members cannot directly access private members of the base class.
2. The public members of a base class can be inherited either as public
members or as private members by the derived class.
3. The derived class can include additional members-data and/or functions.
4. The derived class can redefine the public member functions of the base class.
5. All member variables of the base class are also member variables of the derived class.
6. All member functions of the base class are also member variables of the derived class.
BASE CLASS
 Suppose that you want to design the class rectangle to implement and
process the characteristics of a rectangle shape.

1. width = w
2. height = h
Shape
+ setWidth (int): void
+ setHeight (int): void

# width: int
# height: int
DERIVED CLASS

1. Build a derived class


2. Use it for computing its area
3. Assign values through MAIN function
4. Use the base class variables in the computation of rectangle
area
Rectangle
+ getArea (int)
INHERITANCE ADVANTAGES

• Inheritance allows us to define a class in terms of another


class.
• Easy to create and maintain an application.
• Reuse the code functionality and fast implementation time.
ACCESS TYPE

Access public protected private


Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no


MULTIPLE INHERITANCE
• class derived-class: access baseA, access baseB....
• Example:
• Create PainCost base class
• Derive Rectangle from both classes (Shape, PaintCost).

Shape PaintCost Rectangle


+ setWidth (int): void + getCost (int) + getArea (int)
+ setHeight (int): void

# width: int
# height: int
NEXT MEETING
REDEFINING (OVERRIDING)

 Redefining (overriding) a member function of the base class.


 Use the same name or a new name for a function member defined in
baseclass (super-class or parent class) within a derivedclass.
 Derived class (child class) provides different implementation to a
parent class function.
REDEFINING (OVERRIDING)
 Example: base class:
REDEFINING (OVERRIDING)
 BoxType is a Derived class from RectangleType super-class:
REDEFINING (OVERRIDING)
 Public Inheritance: all public members of rectangleType class are public to boxType.
 boxType overrides (redefines) the function of prints & area as follows:
 Call statement syntax in the definition part is: baseclass :: function name
void boxType::print() const
{
rectangleType::print();
cout << " Height = "<< height;
}
 Length & Width are accessible by boxType ONLY through public functions of
rectangleType.
OVERRIDING – WRITE THE DEFINITION OF FUNCTION

• void boxType::print() const


• void boxType::setDimension(double l, double w, double h)
• double boxType::getHeight() const
• double boxType::area() const
• double boxType::volume() const
• boxType::boxType()
• boxType::boxType(double l, double w, double h)
BOXTYPE FUNCTION DEFINITION
 The member function area of the class boxType determines the Surface area of a
box : 2(h × W) + 2(h × L) + 2(W × L)
 We need to to access the length and width (private members of the class
rectangleType).
 Use getLength and getWidth of the class rectangleType to retrieve the length
and width, respectively.
double boxType::area() const
{
return 2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height);
}
BOXTYPE FUNCTION DEFINITION

 The member function volume determines the volume of a box.


 Multiply the length, width, and height of the box or multiply the area of
the base of the box by its height.
double boxType::volume() const
{
return rectangleType::area() * height;
}
CONSTRUCTORS OF DERIVED AND BASE CLASSES

 A derived class can include its own constructors since it can contain private
members.
 Derived class object cannot directly access the private (data) members of the
base class.
 The same is true for the member functions of a derived class.
 So, constructors of a derived class can (directly) initialize only the (public
data) members inherited from the base class.
 Derived class object triggers the execution of one of the base class’s
constructors. Done when create the derived class header definition.
CONSTRUCTORS OF DERIVED AND BASE CLASSES

 boxType constructor heading includes all of the parameters needed.


 To trigger the execution of the base class constructor:
 Add a colon (:).
boxType::boxType(double l, double w, double h)
:rectangleType(l, w)
{
if (h >= 0)
height = h;
else
height = 0;
}
VALUE AND CALLING STATEMENTS

 Consider the following statements:


rectangeType myRectangel(5.0, 3.0);
boxType myBox(6.0, 5.0, 4.0);

myrectangle.print();
cout << endl;
mybox.print();
cout <<endl;
VALUE AND CALLING STATEMENTS

 When a derived class constructor executes:

1. first a constructor of the base class executes to initialize the data


members inherited from the base class (length & width).
2. and then the constructor of the derived class executes to initialize the
data members declared by the derived class (height).
CASE 1
 Solve the following problems: Jim’s lawn care store specializes in putting up fences
around small farms and home lawns and fertilizing the farms and lawns.
 For simplicity, we assume that the yards and farms are rectangular. In order to put up the
fence, the program needs to know the perimeter, and to fertilize, the program needs to
know the area.
1. Use the class rectangle to store the dimensions of a yard or a farm.
2. Prompt the user to input the dimensions (in feet) of a yard or farm.
3. Fence cost (per foot).
4. Cost (per square foot) to fertilize the area.
5. Output the cost of putting up the fence and fertilizing the area.
CASE 2

 Linda’s gift store specializes in wrapping small packages.


 For simplicity, we assume that a package is in the shape of a box with a specific length,
width, and height.
 We will write a program that uses the class boxType to store the dimensions of a package.
 The program will ask the user to:
1. input the dimensions of the package.
2. Input the cost (per square foot) to wrap the package.
 Output the cost of wrapping the package.
 The program assumes that the minimum cost of wrapping a package is $1.00.)
DESTRUCTORS IN A DERIVED CLASS

 When a derived class object goes out of scope, it automatically invokes its
destructor.
 When the destructor of the derived class executes, it automatically invokes the
destructor of the base class.
 So when writing the definition of the destructor of the derived class, an explicit
call to the destructor of the base class is not needed.
 Furthermore, when the destructor of the derived class executes, it executes its
own code first and then calls the destructor of the base class.
HEADER FILE OF A DERIVED CLASS

 When base classes are already defined, and header files contain their definitions.
 The header files of the new classes contain commands that tell the computer where to
look for the definitions of the base classes.
 class personType is placed in the header file personType.h.
 To create the definition of the class partTimeEmployee.
 partTimeEmployee.h—must contain the preprocessor directive:
#include "personType.h
MULTIPLE INCLUSIONS OF A HEADER FILE
 Suppose you have header file of test.h
//Header file test.h
const int ONE = 1;
const int TWO = 2;

 testA.h includes the file test.h in order to use the identifiers ONE and TWO and
looks as:
//Header file testA.h
 Which of these files execute first?
#include "test.h"  //Header file test.h
 //Header file testA.h
.  //Program headerTest.cpp
 Consider the following code:
 This implementation generates Run
//Program headerTest.cpp
time error. Why?
#include "test.h"

#include "testA.h"

.
MULTIPLE INCLUSIONS OF A HEADER FILE
 Void multiple inclusions:
//Header file test.h
#ifndef H_test
#define H_test
What is the effect of these statements?
const int ONE = 1;
const int TWO = 2;
#endif

1. #ifndef H_test means “if not defined H_test”


2. #define H_test means “define H_test”
3. #endif means “end if”
C++ STREAM CLASSES

C++ stream classes hierarchy


INHERITANCE AS PUBLIC
 When member of a base class needs to be accessed by a derived class, that member is
declared under memberAccessSpecifier protected.
 memberAccessSpecifieris either public, protected, or private.
 Suppose class B is derived from class A:
INHERITANCE AS PROTECTED
INHERITANCE AS PRIVATE
COMPOSITION (AGGREGATION)

 It is another way to relate two classes.


 One or more members of a class are objects of another class type.
 It is “has-a” relation; for example, “every person has a date of
birth.”.
 The class personType stores a person’s first and last name.
 Every person has a personal ID and a DoB.
 In Aggregation, the new class is made up of other existing classes.
COMPOSITION (AGGREGATION)

Definition of dateType class:

class dateType {

public:

private:
dMonth = month;
dDay = day;
dYear = year;
};
COMPOSITION (AGGREGATION)

Definition of personalInfo class:

class personalInfo
{
public:

private:
personType name;
dateType bDay;
int personID;
};

What are the members name and bDay?


OOD & OOP

 The three basic principles of OOD are as follows:


 Encapsulation—The ability to combine data and operations on that data in a single
unit.
 Inheritance—The ability to create new objects (classes) from existing objects (classes).
 Polymorphism—The ability to use the same expression to denote different operations.

 In OOD, a program is a collection of interacting objects; in structured


programming, a program is a collection of interacting functions.
 Object-oriented programming (OOP) implements OOD.
THE CHAPTER END

You might also like