Partial preview of the text
Download Extended classes using inheritance and more Study notes Object Oriented Programming in PDF only on Docsity!
GOVERNMENT POLYTECHNIC KOLHAPUR (Autonomous) - Information Technology C++ Programming CHAPTER 04 Unit Ill: Extending Classes Using Inheritance Corrected, Complete & Exam-Oriented Notes Based on original classroom notes - preserved topic order, corrected for modern C++ (GCC / Dev-C++). No Turbo C++ functions like cirscr(), getch(), conio.h or are used. Contents: Inheritance Intro | Visibility Modes | Single | Multiple | Hierarchical | Multilevel | Hybrid | Multipath | Virtual Base Class | Abstract Class | Constructors in Derived Classes | ‘Order of Constructor Execution How to use: Read definition -> see diagram -> read program line-by-line -> run it yourself -> remember Exam Point box. Student-prepared notes - For study purpose 1 Inheritance - Introduction Definition: Inheritance is the capability of one class to acquire properties and characteristics from another class. The class whose properties are inherited is called Parent / Base / Super class. The class which inherits is called Child / Derived / Sub class. Inheritance makes code reusable. When we inherit an existing class, all its methods and fields become available in the new class, hence code is reused. Example: Vehicle has start() and stop(). Car inherits Vehicle, so Car also gets start() and stop() without writing them again. Purpose of Inheritance 1. Code Reusability - Write once, use in many classes. 2. Method Overriding - Derived class can redefine base class function (hence Runtime Polymorphism). 3. Use of Virtual Keyword - For virtual functions and virtual base classes. Defining a Derived Class - Syntax of Inheritance ‘Syntax - Inheritance elass Subelass_name : access_mode Superclass_name ( // body of subclass Ve While defining a derived class, the base class must be already defined or at least declared before the derived class declaration. Visibility Modes and Effects Access Mode specifies in which mode properties of superclass will be inherited into subclass - public, private or protected. 1) Public Inheritance - Most used mode Protected member of super class becomes protected in sub class, and public becomes public. ‘Syntax - Public class Subclass : public Superclass { // body Me 2) Private Inheritance - Default in C++ Protected and public members of super class become private members of derived class. ‘Syntax - Private Glass Subclass : Superclass // By default private ce // body i // Same as: class Subclass : private Superelass 3) Protected Inheritance Public and protected members of super class become protected members of sub class. 2 Single Inheritance Definition: In Single Inheritance, one derived class inherits from only one base class. It is the simplest form of inheritance. Base Class: Vehicle | Derived Class: Car Syntax - Single class Subclass_name : access_mode Base_class { J/ body of subclass i Program 1 - Single Inheritance (Corrected) Correction: Original comment wrongly said ‘derived from two base classes’. Car inherits from only ONE base class - Vehicle. Program 1 - Single Inheritance #include using namespace std; élass Vehicle // Base class { public: Vehicle() { cout << "This is a Vehicle" << endl; he class Car : public Vehicle // Derived from ONE base class ( he int main() { Car obj; // Base constructor called automatically return 0; Expected Output This is a Vehicle Explanation: When Car obj is created, first Vehicle() runs, then Car() (default, empty) tuns. 3 Multiple Inheritance Definition: In Multiple Inheritance, a single derived class inherits from two or more than two base classes. Base: Vehicle Base: FourWheeler \ / Derived: Car ‘Syntax - Multiple class Subclass_name : access_mode Basel; access_mode Base2, ... { // body of subclass Me Base classes are separated by comma (,) and access mode for every base class must be specified. Program 2 - Multiple Inheritance (Corrected) Program 2- Multiple Inheritance finclude using namespace std; class Vehicle // First base class ( public: Vehicle() { cout << "This is a Vehicle" << endl; Me class FourWheeler // Second base class { public: FourWheeler () { cout << "This is a 4 wheeler Vehicle" << endl; Me // Sub class derived from TWO base classes class Car : public Vehicle, public FourWheeler ( Ve int main() { Car obj; return 0; Expected Output This is a Vehicle This is a 4 wheeler Vehicle Order: Base constructors called in order of inheritance - Vehicle first, then FourWheeler, then Car. 5 Multilevel Inheritance Definition: In Multilevel Inheritance, the derived class inherits from a class, which in turn inherits from some other class. The super class for one, is sub class for the other. Vehicle (Base) | FourWheeler (Intermediate) | Car (Derived) Program 4 - Multilevel Inheritance (Corrected) Correction: Constructor was written as car() with small 'c'. Constructor must have SAME name as class - Car() with capital C. Wrong comment corrected. Program 4 - Multilevel Inheritance #include using namespace std; class Vehicle // Base class { public: Vehicle() { cout << "This is a Vehicle" << endl; Vi class FourWheeler : public Vehicle { public: Fourtiheeler () { cout << "Objects with 4 wheels are vehicles" << endl; Vi class Car : public FourWheeler // Derived from FourWheeler only { public: Car() // CORRECT: Capital Cc, same as class name { cout << "Car has 4 Wheels" << endl; be int main() ( Car obj; return 0; Expected Output This is a Vehicle Objects with 4 wheels are vehicles Car has 4 Wheels Order: Top to bottom - Vehicle -> FourWheeler -> Car. Base first, derived last. 6 Hybrid Inheritance Definition: Hybrid Inheritance is a combination of two or more types of inheritance - for example Hierarchical + Multilevel, or Multiple + Single. It is also called Hybrid (Virtual) Inheritance when virtual base class is used to avoid duplication. Original notes Hybrid example was actually just Multiple Inheritance (Bus : Vehicle, Fare). It did NOT show hybrid. Below is CORRECTED example that truly shows hybrid: Hierarchical + Multilevel combined. Vehicle (Base) / \ Car FourWheeler | SportsCar (Hybrid) Explanation: Vehicle -> Car and Vehicle -> FourWheeler is Hierarchical. FourWheeler -> SportsCar is Multilevel. SportsCar also uses Car via Multiple. So combination = Hybrid. Program 5 - Hybrid Inheritance (Corrected - Actually Hybrid) 7 Multipath Inheritance Definition: Multipath Inheritance occurs when a Child has two direct base classes Parent! and Parent2, which themselves have a common base class Grandparent. The Child inherits Grandparent via two separate paths. Grandparent (A) a \ Parentl (B1) Parent2 (B2) \ u Child (C) All public and protected members of Grandparent are inherited into Child TWICE - first via Parent1 and again via Parent2. This means Child would have duplicate sets of members. This introduces ambiguity and should be avoided. This duplication can be avoided by making common base class (ancestor) a VIRTUAL base class while declaring direct / intermediate base classes. ‘Syntax - Virtual Base Class class A // Grandparent { be class Bl : virtual public A // Parentl { i class B2 : public virtual A // Parent2 - same meaning ( be class C : public Bl, public B2 // Child { // Only ONE copy of A will be inherited Ve When a class is made a virtual base class, C++ takes care that only ONE copy of that class is inherited, regardless of how many paths exist. Keywords virtual and public may be used in either order: ‘virtual public A’ and ‘public virtual A’ both correct. Exam Point - Draw Multipath diagram + 'Why virtual base class?" - Answer: To avoid duplicate copy and ambiguity of Grandparent members in Child. 8 Virtual Base Classes - Program This is the famous Student -> Test, Sports -> Result example from original notes. It is classic multipath problem: Result inherits Test and Sports, both inherit Student. Without ‘virtual’, Result would get two copies of Student (rallNo). With ‘virtual’, only one copy. Student (virtual base) / \ Test Sports \ t Result Program 6 - Virtual Base Classes (Fully Corrected) Corrections: -> , removed conio.h / clrscr() / getch(), void main() -> int main(), putScore() wrongly printed ‘Enter Sports Score’ - corrected to ‘Sports Score:’, names capitalised consistently. Program 6 - Virtual Base Classes finclude using namespace std; class Student ( protected: int rollNo; public: void getRol1No()j void putRol1No(); i void Student: :getRallNo() ( cout << "\nEnter Roll No: "7 cin >> rollNo; } void Student: :putRallNot) { cout << "\nRoll No : " << rollNo; 1 class Test : virtual public Student { protected: float marksl, marks2; public: void getMarks(); void putMarks(); hi void Test: :getMarks() { cout << "\nEnter Marks of Testl : "7 cin >> marksl; cout << "\nEnter Marks of Test2 : "7 cin >> marks2; 1 void Test: :putMacks({) ( cout << "\nMarks in Testl : " << marks; cout << "\nMarks in Test2 + " << marks2; ) class Sports : public virtual Student 9 Abstract Classes Definition: An Abstract Class is a class that contains at least ONE pure virtual function and cannot be used to create objects. It is designed only to act as a base class (to be inherited). It provides a base upon which other classes may be built. Correction to original notes: Original said ‘Student class is abstract because it was not used to create objects.' That is WRONG reason. A class is abstract only if it has a pure virtual function - not just because we did not create its object. ‘Syntax - Pure Virtual Function class Shape // Abstract class { public: virtual void draw() = 0; // Pure virtual function // = 0 means no body, derived MUST define it Me Rules: Cannot create object of abstract class: Shape s; -> ERROR. Can create pointer / reference: Shape *p; -> Allowed. Derived class MUST define all pure virtual functions, otherwise derived also becomes abstract. Abstract class can have normal functions and data members also. Program 7 - Abstract Class (To make concept clear) Program 7 - Abstract Class finclude using namespace std; class Shape // Abstract class - has pure virtual function { public: virtual void draw() = 0; // Pure virtual function void info() 4 cout << "This is a Shape” << endl; i ¢lass Circle : public Shape { public: void draw() 4 cout << "Drawing Circle" << endl; de class Rectangle : public Shape ( public: void draw() 1 cout << "Drawing Rectangle" << endl; Me int main() { // Shape s; // ERROR - cannot create object Circle ¢; Rectangle r; c.info{ c.draw(); redraw(); return 0; Expected Output This is a Shape Drawing Circle Drawing Rectangle Exam Point - Define Abstract Class in 1 line: ‘A class with at least one pure virtual function, which cannot be instantiated.’ Always write ‘virtual void draw() = 0;' - examiner expects '= 0". Expected Output Base Parameterized Constructor x= 10 Derived Parameterized Constructor y = 20 Explanation: Derived d(10, 20) -> j=10 goes to Base(j), so Base gets 10. K=20 stays in Derived as y. Base prints first, Derived second. Order of Constructor Execution For Multiple Inheritance: Base constructors are called in ORDER OF INHERITANCE (order written in class declaration), then derived constructor. ‘Syntax - Order in Multiple class Child : public Parentl, public Parent2 // Parenti first, then Parent2, then Child Program 9 - Order of Constructor Calls in Multiple Inheritance (Corrected) Program 9 - Order of Constructors include using namespace std; class Parent1 { public: Parentl() { cout << "Inside first base class" << endl; M class Parent2 { public: Parent2() ( cout << "Inside second base class" << endl; hi class Child : public Parent1, public Parent2 { public: Child() { cout << “Inside child class" << endl; he int main() { Child obj1; return 0; Expected Output Inside first base class Inside second base class Inside child class Revision - Advantages, Applications & Exam Points Advantages of Inheritance - Code Reusability - No need to rewrite same code. Less development time and less testing. Easy maintenance - Change in base reflects in all derived. Supports Polymorphism and Method Overriding. Helps in building hierarchical classification - Vehicle -> Car / Bus. Applications GUI frameworks, Game development, Banking - Account -> Saving / Current. College system - Person -> Student / Teacher. Library, Hospital, Railway reservation systems.