I'm reading Thinking in C++ by Bruce Eckel. In Chapter 15 (Volume 1) under the heading "Behaviour of virtual functions inside constructor", he goes
What happens if you’re inside a constructor and you call a virtual function? Inside an ordinary member function you can imagine what will happen – the virtual call is resolved at runtime because the object cannot know whether it belongs to the class the member function is in, or some class derived from it. For consistency, you might think this is what should happen inside constructors.
Here Bruce's trying to explain that when you call a virtual function inside an object's constructor, polymorphism isn't exhibited i.e. the current class' function will only be called and it will not be some other derived class version of that function. This is valid and I can understand it, since the constructor for a class will not know beforehand if it's running for it or for someother dervied object's creation. Moreover, if it does so, it'll be calling functions on a partially created object, which is disastrous.
While my confusion suddenly arose because of the first sentence where he states about the ordinary member function, where he says the virtual call will be resolved @ run-time. But wait, inside any member function of a class, when you call another function (be it virtual or non-virtual) it's own class version will only be called, right? E.g.
class A
{
virtual void add() { subadd(); }
virtual subadd() { std::cout << "A::subadd()\n"; }
};
class B : public A
{
void add() { subadd(); }
void subadd() { std::cout << "B::subadd()\n"; }
};
In the above code, in A::add()
when a call to subadd()
is made, it'll always call A::subadd()
and the same holds true for B
as well, right? So what is he meaning by "the virtual call is resolved at runtime because the object cannot know whether it belongs to the class the member function is in, or some class derived from it" ?
Is he explaining it with respect to a call via a base class pointer? (I really suspect so) In which case he shouldn't be writing "Inside an ordinary member function"; from my understanding so far, any call of a member function from inside another member function of the same class is not polymorphic, please correct me if am getting it wrong.