0

With regards to this answer, why doesn't a non-virtual method of the base class gets "name-hidden" when called via a base class pointer pointing to a derived object? I have edited that post to explain what my doubt is but haven't got any response from the fella who answered my previous doubt.

Community
  • 1
  • 1
Zaid Khan
  • 786
  • 2
  • 11
  • 24

1 Answers1

1

It has nothing to do with name hiding. In the C++ object model an object contains the following: the members (member variables and member functions, the latter occupying no "space"), and, if there is at least one member function is marked virtual, a pointer to the table of virtual functions. Whenever you have something like Base* p = new Derived; p->f();, the compiler proceeds in one of the two possible ways:

  1. If f is marked virtual, the call is translated to p->vpointer[index_of_f_in_vtable]();, i.e. f is called via the pointer to vtable, which has the effect of invoking Derived::f();
  2. If f is not virtual, Base::f() is invoked since the pointer is of type Base.

In your case, there is no virtual table, so Base::f() is invoked.

See e.g. this Wikipedia article for a more detailed explanation.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • So the "name hiding" concept(where the derived class method overrides base class method having the same name) doesn't applies here? – Zaid Khan Sep 20 '15 at 17:11
  • @KhanZaid No, it does not apply here. In the call `p->f();`, the function `f` must be common to both the Base and Derived, with exactly the same signature (up to [covariance of the return type](http://stackoverflow.com/questions/1260757/when-is-c-covariance-the-best-solution)). – vsoftco Sep 20 '15 at 17:15