Re: Vptr
On Aug 10, 3:20 pm, MC <manan.cho...@gmail.com> wrote:
Hi!
I have another naive question. I have been trying to understand the
polymorphysim implementation in C++.
I believe that most of the compilers implement it using vptr and
vtables.
My question is when for every object of a class (which has a virtual
member) if vptr points to the same vtable, why does every object has
a copy of the same vptr?
For example
say X is a class which has a virtual function
and a and b are objects of that class
both a and b will have a vptr installed in them and this vptr will
point to the same vtable
Why not have the vptr as a static data member of the class X so that
every object of that class can use it.
I am sure there is a very good reason for the way it is implemented,
but because of my inexperience with C++ I dont see the reason. Can
anybody please elaborate on the reason.
Consider this program, and ask yourself how the print() function
can possibly work with your suggested implementation.
#include <iostream>
class Base {
public:
virtual void foo() = 0;
virtual ~Base() {}
};
class Derived1 : public Base {
public:
virtual void foo() { std::cout << "Derived1" << std::endl; }
};
class Derived2 : public Base {
public:
virtual void foo() { std::cout << "Derived2" << std::endl; }
};
void print(Base const & base)
{
base.foo();
}
int main()
{
Derived1 d1;
Derived2 d2;
print(d1);
print(d2);
}
The problem is, of course, that while print() works on Base objects,
that's the static type of the object, but the dynamic type is really
*either* Derived1 or Derived2, so in the exact same function, print()
needs to invoke 2 different foo() functions, without knowing the type
of the object on which it's calling.
Thus, d1 and d2 have different vtbl pointers, and inside print(),
the "right" function is called by looking at the object's vtbl,
without
caring what type it is. (Furthermore, in the context of print(),
the static type of the object is wrong, as it's an abstract type,
so it would not be possible to access the data the way you suggest.)
--
Chris
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]