Skip to content

Commit

Permalink
Merge pull request #51 from rpandox/feat/mult-levl-inheritance-q7
Browse files Browse the repository at this point in the history
Feat/mult-levl-inheritance-q7
  • Loading branch information
gaurovgiri authored Oct 22, 2024
2 parents 96844a1 + e14ee49 commit 290657c
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
61 changes: 61 additions & 0 deletions programs/Inheritance/Multilevel Inheritance/q7.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#include <iostream>
using namespace std;

// Base class
class Base {
public:
// Virtual function to enable dynamic dispatch
virtual void display() {
cout << "Display from Base class." << endl;
}

virtual ~Base() {
cout << "Base class destructor called." << endl;
}
};

// Intermediate derived class (inherits from Base)
class Derived1 : public Base {
public:
// Overriding the display function from Base class
void display() override {
cout << "Display from Derived1 class." << endl;
}

~Derived1() {
cout << "Derived1 class destructor called." << endl;
}
};

// Final derived class (inherits from Derived1)
class Derived2 : public Derived1 {
public:
// Overriding the display function again
void display() override {
cout << "Display from Derived2 class." << endl;
}

~Derived2() {
cout << "Derived2 class destructor called." << endl;
}
};

int main() {
// Base class pointer pointing to Derived2 object
Base* basePtr = new Derived2();

// Dynamic dispatch happens here - Derived2's display function is called
basePtr->display();

// Base class pointer pointing to Derived1 object
Base* basePtr2 = new Derived1();

// Dynamic dispatch happens here - Derived1's display function is called
basePtr2->display();

// Clean up: destructors will be called in reverse order
delete basePtr;
delete basePtr2;

return 0;
}
2 changes: 1 addition & 1 deletion programs/Inheritance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
- [x] [q4](./Multilevel%20Inheritance/q4.cpp): WAP to show multilevel inheritance where each class contains its own constructor and destructor.
- [x] [q5](./Multilevel%20Inheritance/q5.cpp): WAP to demonstrate multilevel inheritance with virtual functions.
- [x] [q6](./Multilevel%20Inheritance/q6.cpp): WAP to show multilevel inheritance where the derived class overrides methods from both intermediate and base classes.
- [ ] [q7](./Multilevel%20Inheritance/q7.cpp): WAP to demonstrate multilevel inheritance with method overriding and dynamic method dispatch using pointers.
- [x] [q7](./Multilevel%20Inheritance/q7.cpp): WAP to demonstrate multilevel inheritance with method overriding and dynamic method dispatch using pointers.

## Important

Expand Down

0 comments on commit 290657c

Please sign in to comment.