Reference variable and virtual functions
-
27-10-2019 - |
Question
I've found a strange behavior while using a reference variable.
Here is class implementations:
class Base {
public:
virtual void Method() = 0;
};
class DerivedA : public Base {
public:
virtual void Method() {}
}
class DerivedB : public Base {
public:
virtual void Method() {}
}
Here is an example code which have the strange behavior:
void main(int argc, char *argv[]) {
DerivedA a;
DerivedB b;
Base &base = a;
base.Method(); // Calls DerivedA::Method
base = b;
base.Method(); // Calls DerivedA::Method!!! Why doesn't call DerivedB.Method()?
}
In conclusion, it seems that the virtual function pointer table "associated" to the reference variable is determine only when initializing the reference variable. If I re-assign the reference variable the vfpt doesn't change.
What happens here?
Solution
Base &base
is a reference, i.e. alias to the a
object, so the assignment base = b
is equivalent to a = b
, which leaves the base
thingie still the same object of the same class. It is not a reassignment of pointer as you seem to assume.
OTHER TIPS
References can only be initialized once. You can not assign a new object to a reference. What is actually happening here is that operator= of Base is called and the underlying object is still DerivedA and not DerivedB.