Вы находитесь на странице: 1из 8

Bit 20603 Object Oriented Programming

Chapter 4 Inheritance
Inheritance & Polymorphism

Recall from chapter 1


 Inheritance is a relationship between classes
where one class is the parent class (superclass) of
its child class (subclass)
Defines a relationship among classes where
 Inheritance is also used to communicate the
one class shares the structure and/or concept that one class can inherit part of its
behavior on one or more classes. behavior and data from another class.

 For example, a subclass of a program can inherit


some code from its superclass. In particular, in
specification “B inherits A”, class B contains the
data and methods defined for class A in addition
to those defined for B.

1
Terminology
 C++ inheritance mechanism is used to build new
classes from an existing class Base class = generic class/parent class/superclass

 Classes are allowed to inherits commonly used Derived class = specific class/child class/subclass
state and behavior from other classes.

 The concept of inheritance enhances the ability to


reuse code.

Inheritance
Single Inheritance Multiple Inheritance
Single Inheritance Multiple Inheritance
SuperClass SuperClass SuperClass
 subclass may inherit instance  subclass may inherit instance
variables and methods of a variables and methods from
single parent class, possibly multiple parent classes.
adding some methods and
instance variables of its own. SubClass SubClass SubClass
 the new class subclasses of the SubClass
other class, it does not need to
re-implement the basic
functionality of its
superclasses but needs only to
add its own specialized
behavior and state

2
Single Inheritance
Student

SuperClass

primary Secondary College

SubClass SubClass SubClass


Uniform

Base class Format structure:


access specifier
Single Inheritance
//Super class
class X Y class inherits
class derived_class_name : public base_class_name { members and
{ }; functions from X
private: variables_declaration; //Sub class class
public: methods_declaration; class Y : public X
}; {
};

3
Single Inheritance Single Inheritance
 Suppose we want to model postgraduate and
undergraduate students.
Student
 For both types of student we keep their names, test score
and final course grade.

 The formula of deriving the final course grade for


postgraduate and undergraduate students are different.
Postgraduate Undergraduate
 How shall we implement the two types of student?

Single Inheritance Single Inheritance

class Student class Vehicle


{ public: { public:
char name[20]; int model;
char studentId[8]; }; protected:
int year;};
class Postgraduate : public Student
{ char major[20]; }; class Car : public Vehicle
{ private : string carNo;};
class Undergraduate : public Student
{ char specialization[50]; }; class MPV : public Vehicle
{ private : int backDoor;};

4
Single Inheritance Single Inheritance
Example 4
Introduce class Circle using inheritance from Class Point
class Vehicle class Point{
{ int model; private: class Circle : public Point {
int year;}; int x, y; // point coordinate private :
public: float Result;
class Car : public Vehicle void setX(int val); public:
void setY(int val); Circle(); //constructor declaration
{ string carNo;}
int getX(); void SetPoint();
int getY(); void GetResult();
class MPV : public Vehicle }; // class Point };
{ int backDoor;}

Single Inheritance Example 5


#include <iostream> int main(void) {
using namespace std; Rectangle Rect;

Multiple Inheritance
// Base class Rect.setWidth(5);
class Shape { Rect.setHeight(7);
public:
void setWidth(int w) { // Print the area of the object.
width = w; cout << "Total area: “;
} cout << Rect.getArea() << endl;
void setHeight(int h) {
height = h; return 0;
SuperClass SuperClass
} }

protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape {
public:
int getArea() { SubClass
return (width * height);
}
};

5
Base class access
specifier
Multiple Inheritance Multiple Inheritance

class derived_class : public base_class1, public base_class2


{ Student Instructor
private: variables_declaration;
public: methods_declaration;
};

TeachingAssistant

Multiple Inheritance Example 7


#include <iostream> // Derived class
using namespace std; class Rectangle: public Shape, public
Multiple Inheritance Example 6 PaintCost {
// Base class Shape public:
class Shape { int getArea() {
public: return (width * height); }
class Student void setWidth(int w) { };
{ public: width = w;
} int main() {
double cgpa; void setHeight(int h) { Rectangle Rect;
char studentId[8]; }; height = h; int area;
}
Rect.setWidth(5);
class Instructor protected: Rect.setHeight(7);
{ public: int width; area = Rect.getArea();
char FacultyCode[2]; int height;
}; // Print the area of the object.
char StaffId[5]; };
cout << "Total area: “;
// Base class PaintCost cout << Rect.getArea() << endl;
class PaintCost {
class TeachingAssistant : public Student, public Instructor public: // Print the total cost of
int getCost(int area) { painting
{ char CourseCode[8]; }; return area * 70; cout << "Total paint cost: $“;
} cout << Rect.getCost(area)<< endl;
}; return 0;
}

6
Polymorphism

Polymorphism Concept:
 Polymorphism means having many forms.
 Provides the ability to use a single message to invoke
many different kinds of behavior.
 Methods with the same name with different meaning.
 The methods must belong to different kinds of
objects
 Polymorphism also allows significant code sharing
and code reuse

Polymorphism
Polymorphism
#include<iostream> int main()
using namespace std; {

Example 1 class Base{


public:
Base objbase;
Derive1st objder1st;
void DisplayDetails(){ Derive2nd objder2nd;
Base cout<<"Hello I am the base class"<<endl;
} objbase.DisplayDetails();
}; objder1st.DisplayDetails();
objder2nd.DisplayDetails();
• DisplayDetails class Derive1st : public Base{
public: }
void DisplayDetails(){
cout<<"Hello I am the 1st derive
class"<<endl;
Hello I am the base class
}
Derive1st Derive2nd Hello I am the 1st derive class
};
Hello I am the base class
class Derive2nd : public Base{
• DisplayDetails • Show public:
void Show(){
cout<<"Hello I am the 2nd derive
class"<<endl;
}
};

7
Polymorphism Polymorphism
Example 2
Virtual Function (page 98 text book)
Shape

• For polymorphism, C++ also introduces virtual function for abstraction


and dynamic binding. Shape()
+area_calc() : double

• Virtual functions are used in C++ to ensure that the correct function is
called from the appropriate derived class.

Rectangle Circle
• This is done at run time where dynamic binding occurs. +width +radius
+height
Rectangle(double w, double h) Circle(double r)
+area_calc() : double +area_calc() ; double

Polymorphism
#include <iostream> class Circle : public Shape{
#define PI 3.14159 public:
using namespace std; double radius;
Circle(double r = 2) { radius = r; }
class Shape //Base class{ double area_calc(){
public: return PI*radius*radius;
Shape() {} }
virtual double area_calc() { };
return 0; } ’.
}; int main(){ Rosziati Ibrahim and Sapiee Jamel (2006), “ Object-Oriented
Circle circ; Programming Using C++: An Introduction”,McGrawHill Sdn.
class Rectangle : public Shape{ Rectangle rect; Bhd, Malaysia.
public: Deitel, H.M and Deitel P.J( 2005),” C++ How To Program
double width, height; Shape* ptr = &circ; Fifth Edition”, Pearson Education, Inc., New Jersey.
Rectangle(double w = 2, double cout << "circ area: " << ptr-  Koffman, Elliot B. and Wolfgang, Paul A.T (2006),”Objects, Abstraction,
h = 2){ >area_calc() << endl;
Data Structures and Design Using C++”, John Wiley and Sons,US.
width = w; height = h;
Gaddis, T. et al (2008), “Starting Out with C++ Early Objects”, Pearson
} ptr = &rect; //ptr -> rect
double area_calc(){ cout << "rect area: " << ptr-
Education, Inc.
return width*height; >area_calc() << endl;
}
}; cout << "circ area: " <<
circ.area_calc() << endl;
return 0;
}

Вам также может понравиться