0

Here are two classes that overload a virtual function:

class Base
{
public:
    virtual void func(int) {
        cout<<"base int"<<endl;
    }
    virtual void func(double) {
        cout<<"base double"<<endl;
    }
};

class Deri: public Base
{
public:
    virtual void func(int) {
        cout<<"deri int"<<endl;
    }
};

I use these classes here:

int main() {
    Base * ptr = new Deri;
    ptr->func(3.0);                     //"base double"
    static_cast<Deri *>(ptr)->func(3.0);//"deri int"
    return 0;
}

I expected that both calls are for the base double overload, but I get the following output:

base double 
deri int  

When I add the following "using" statement in Deri:

using Base::func; 

I get all overloaded functions from the Base class and it works as expected.

What happens when I don't use this "using statement" ? I assume ptr->func(3.0) and static_cast<Deri*>->func(3.0) look for the same vtable. But how they look for different functions? What the vtable of Class Deri look like?

Christophe
  • 68,716
  • 7
  • 72
  • 138
ubc_ben
  • 163
  • 1
  • 10

1 Answers1

0

Look at here:http://thesyntacticsugar.blogspot.ca/2011/10/behind-scenes-name-hiding-in-c.html

It said that "When identifying possible candidates, name lookup propagates outward starting from the immediate scope. Only if no function exists with the correct name does the process continue to the next enclosing scope. Once a scope is found that has at least one viable candidate, the compiler proceeds with matching the arguments to the parameters of the various candidates, applying access rules etc".

So my understanding is the type of the pointer detemines which scope the name lookup starts. When it is the pointer of the Base class, it looks up in Class Base first. When static_cast to the Deri class, it looks up in Class Deri first.

It is notable that all three versions of func() are in the vtable of Class Deri.

ubc_ben
  • 163
  • 1
  • 10