320 likes | 340 Views
This article provides an introduction to inheritance in object-oriented programming and explains the basics of inheritance. It covers topics such as the general form of a class, how specialized classes are defined, inheriting properties of a general class, and adding new data members and functions.
E N D
Learning Objectives • Inheritance • Virtual Function
Introduction to Inheritance • General form of class is defined • Specialized class is then defined • Inherit properties (data member and function member) of general class • Add new data members • Add new functions or modify inherited functions
Inheritance Basics • Base class (parent class) • "General" class from which others derive • Derived class (child class) • Automatically has base class’s: • Member variables • Member functions • Can then add additional member functionsand variables and redefine existing functions
Employee Example: Base Class • General concept of employee helpful! • All have names • All have social security numbers • Associated functions for these "basics" aresimilar among all employees • So "general" class can contain all these"things" about employees
Employee Example (base class) Class Employee { private: string name; string SSN; public: Employee (string, string); void print_check(); };
Employee Example (base class) • Look at function print_check(), different checks should be printed for different types of employees • So, let’s write it like this Employee:: void print_check() { cout << "This function is left for derived class"; }
Employee Example (derived class) • A specific employee could be either a: • Monthly employee (salary is calculated monthly) • Hourly employee (salary is calculated hourly) • Each is a type of employee
Public interitance • class DerivedClass : public BaseClass{ … //public keyword (most commonly used) //specifies "publicly inherited“ from //Employee class //other keywords (protected, private) are //rarely used …… };
Employee Example: Derived Class • Define Monthly_Employee and Hourly_Employee as the derived class of general (base) class Employee • From base class • Inherit all member variables • Inherit all member functions • Can then • Define new member functions • Redefine inherited functions
MonthlyEmployee Class class MonthlyEmployee : public Employee { private: double wage; //new data member public: MonthlyEmployee(string, string, double) // constructor void reset_wage(double); // new function member void print_check(); // redefine function member };
HourlyEmployee Class class HourlyEmployee : public Employee { private: double wageRate; //new data member double hours; //new data member public: HourlyEmployee(string, string, double, double) // constructor void reset_wage(double); // new function member void print_check(); // redefine function member };
Constructors in Derived Classes • Base class constructors are NOT inherited in derived classes! • But they can be invoked within derived class constructor • Base class constructor must initialize allbase class member variables • Derived needs to initialize all new data members
Derived Class Constructor Example • MonthlyEmployee constructor: MonthlyEmployee::MonthlyEmployee(string Name, string Number, double wage): Employee(Name, Number) { this->wage = wage; }
Derived Class Constructor Example • HourlyEmployee constructor: HourlyEmployee::HourlyEmployee(string Name, string Number, double wageRate, double hours): Employee(Name, Number) { this->wageRate = wageRate; this->hours = hours; }
Function Redefinition In Derived Class void MonthlyEmployee:: print_check() { cout << wage; } void HoulyEmployee:: print_check() { cout << wageRate*hours; }
Redefining vs. Overloading • Very different! • Redefining in derived class: • SAME parameter list • Essentially "re-writes" same function • Overloading: • Defined "new" function that takes different parameters • Overloaded functions must have different signatures
Accessing Redefined Base Function • When function is redefined in derived class, base class’s definition is not "lost" • Can specify it’s use:Employee JaneE;HourlyEmployee SallyH;JaneE.printCheck(); //calls Employee’s printCheck functionSallyH.printCheck(); //calls HourlyEmployee printCheck functionSallyH.Employee::printCheck(); //Calls Employee’s printCheck function! • Not typical here, but useful sometimes
Destructors in Derived Classes • Base class destructor handles data defined in base class • Derived class destructors handles derived class variables • When derived class destructor is invoked: • Automatically calls base class destructor! • So no need for explicit call
Destructor Calling Order • Consider:class B derives from class Aclass C derives from class B • When object of class C goes out of scope: • Class C destructor called 1st • Then class B destructor called • Finally class A destructor is called • Opposite of how constructors are called • Class A constructor is called • Class B constructor is called • Class C constructor is called
Base Class Member Qualifier class DerivedClass : public BaseClass { private: <members> public: <members> protected: <members> };
Base Class Private Data • Derived class "inherits" private membervariables • But still cannot directly access them • Not even through derived class memberfunctions! • Private member variables can ONLY beaccessed "by name" in member functions of the class they’re defined in
The protected: Qualifier • New classification of class members • Allows access "by name" in derived class • In other classes, these members act like private
"Is a" vs. "Has a" Relationships • Inheritance • Considered an "Is a" class relationship • e.g., a car is a vehicle • e.g., a computer is a machine • e.g., a dog is an animal • A class contains objects of another classas it’s member data • Considered a "Has a" class relationship • e.g., a car has an engine • e.g., a computer has a CPU • e.g., a dog has four legs
Multiple Inheritance • Derived class can have more than onebase class! • Syntax just includes all base classesseparated by commas:class derived: public base1, base2{…} • Dangerous undertaking! • Some believe this should never be used
Virtual Function Basics • Polymorphism • Associating many meanings to one function • Virtual functions provide this capability • Polymorphism, virtual function, and dynamic (late) binding talk about the same thing
Figures Example • Classes for several kinds of figures • Rectangle, Circle, Oval, Square, etc. • Each is an object of different class • Rectangle data: height, width, center point • Circle data: center point, radius • All derive from one parent-class: Figure • Each class needs different draw function Rectangle r;Circle c;r.draw(); //Calls Rectangle class’s drawc.draw(); //Calls Circle class’s draw
Figures Example (continued) • How about this one? void function(Figure f) { f.draw(); } • We would like different draw functions being called for different type of f • Standard non-virtual function can not do this • Virtual functions are the answer
Virtual: How? • Virtual function virtual return_type function_name(parameters) • Involves late binding (dynamic binding) • Tells compiler to "wait" until function is used in program • Decide which definition to use based oncalling object at runtime
Overriding • Virtual function definition changed in a derived class • We say it’s been "overridden" • Similar to “redefined” standard (non-virtual) functions • So, in derived class: • Virtual functions changed: overridden • Non-virtual functions changed: redefined • Seem same for the programmer, but treated differently by the compiler: early binding or late binding
Pure Virtual Functions • Base class might not have "meaningful“ definition; It’s purpose solely for others to derive from • Recall class Figure • All real figures are objects of derived classes • Rectangles, circles, triangles, etc. • Class Figure has no idea how to draw! • Make it a pure virtual function:virtual void draw() = 0; • Pure virtual function • No definitions in based class • Must be overridden in derived classes
Abstract Class • A class with one or more pure virtual functions is called an abstract class • An abstract class can only be used as a base class to derive other classes • We can not create objects of an abstract class, because it is not a complete class definition.