diff --git a/CPP/28.2-virtual-tables.md b/CPP/28.2-virtual-tables.md index c1b6586..de67537 100644 --- a/CPP/28.2-virtual-tables.md +++ b/CPP/28.2-virtual-tables.md @@ -10,29 +10,24 @@ Let's consider the following example: ```cpp class Base { -public: - virtual void function1() { - std::cout << "Base::function1" << std::endl; - } + public: + virtual void function1() { std::cout << "Base::function1" << std::endl; } - virtual void function2() { - std::cout << "Base::function2" << std::endl; - } + virtual void function2() { std::cout << "Base::function2" << std::endl; } }; class Derived : public Base { -public: + public: void function1() override { std::cout << "Derived::function1" << std::endl; } - void function3() { - std::cout << "Derived::function3" << std::endl; - } + void function3() { std::cout << "Derived::function3" << std::endl; } }; int main() { - Base* obj = new Derived(); // create a Derived object and assign a pointer of type Base* + Base* obj = new Derived(); // create a Derived object and assign a pointer + // of type Base* obj->function1(); // calls Derived::function1, due to dynamic polymorphism obj->function2(); // calls Base::function2 @@ -49,3 +44,7 @@ In this example, when a `Derived` object is created, the compiler generates a Vt The `_vptr_` pointer in the `Derived` object points to this Vtable. When the `function1` is called on the `Base` pointer pointing to the `Derived` object, the function pointer in the Vtable is used to call the correct function (in this case, `Derived::function1`). Similarly, the call to `function2` calls `Base::function2`, since it's the function pointer stored in the Vtable for `Derived` class. Note that `function3` is not part of the Vtable, as it is not a virtual function. + +## Diagram explanation + +![image](https://github.com/Rishabh672003/Programming-Notes/assets/53911515/dfc6208d-810e-4f51-9997-5473c1fb7f3f)