Skip to content

Commit

Permalink
updated virtual tables
Browse files Browse the repository at this point in the history
  • Loading branch information
Rishabh672003 committed Dec 25, 2023
1 parent d2de630 commit abb1613
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/28.2-virtual-tables.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)

0 comments on commit abb1613

Please sign in to comment.