Topic04 Inheritance
Topic04 Inheritance
Topic 04
Inheritance
2
Class Inheritance
Example
Person
Student Professor
Example (cont.)
• The classes Student and Professor inherit all attributes
of the class Person
– They can also define their own attributes
Inheritance in C++
• To specify that a class inherits from another class in
C++, you need to use the following syntax
class <base_class> {
...
};
public:
Student(int, string, string); // constructor
...
private:
string fname;
string lname;
int id;
};
public:
UndergradStudent (int, string, string); //Constructor
void setGrade( float, float, float );
private:
float assignment;
float midterm;
float final;
};
• Note:
– The attributes fname, lname and id are inherited from
the class Student
– Each class has its own constructor
9
• Example
private:
float assignment;
float midterm;
float final;
};
10
• Example is on Moodle.
12
• Examples:
– A student is a person
– A professor is a person
– An undergraduate student is a student, which is a person
– A rectangle is a shape
– A car is a vehicle
13
Types of Inheritance
• There exist three types of access specifiers
with inheritance:
– public: class Derived : public Base { ... };
– protected: class Derived : protected Base { ... };
– private: class Derived : private Base { ... };
• Protected inheritance:
– The public and protected members of the base class
become protected members of the derived class
– The private members stay private
19
Function Overriding
• The derived class can redefine the inherited member
functions
– This is known as function overriding
Example
class Employee {
public:
Employee(string, string);
void print() const;
protected:
string fname;
string lname;
};
}
24
public:
HourlyWorker(string, string, double, double);
double getPay() const;
void print() const;
private:
double wage;
double hours;
};
// constructor
HourlyWorker::HourlyWorker(string pf, string pl, double w, double h)
: Employee( pf, pl ) {
wage = w;
hours = h;
}
return wage*hours;
}
25
Multiple inheritance
• Single inheritance: one base class as a parent
class in the inheritance hierarchy
Professor
UndergraduateStudent GraduateStudent
28