Reputation: 331
If Base is a base class and Derived a derived class and there are 25 instances of Derived, how are the vtables set up to be accessed by all the instances? Where are they loaded in the memory?
Upvotes: 6
Views: 1485
Reputation: 1907
Compilers are allowed to implement dynamic dispatch however they want in c++, i don't think there is actually any requirement to even use a vtable at all, but it would be very unusual to find a compiler that didn't.
In most cases i think that each class (that contains some virtual methods) will own a single vtable (so if i had 5 instances of class A
i will still only have 1 vtable), but this behaviour should not be relied upon in any way.
Non virtual classes have no need for vtables as far as i know.
Reading your question it seems as if you think that each object has its own copy of the code, I'm not sure and i don't want to accuse you of anything like that but just in case ...
Google something like: "what does a c++ object look like in memory"
Upvotes: 3
Reputation: 30035
There will be one vtable somewhere in memory, probably in the same place as the code. Each instance of the class will contain a single pointer to the vtable for that class, so in your case all 25 instances will contain a pointer to one copy of the vtable.
Multiple and virtual inheritance complicate things, but the principle is the same.
Upvotes: 5