why does pointer to member conversion from base to derived gives error


Keywords:c++ 


Question: 

If conversion from pointer to Base member To pointer to Derived class member is valid, why does the following code fails to compile

class Base
{
public:
    virtual void fun1()
    {
        cout<<"fun1 in Base"<<endl;
    }
};

class Der
{
public:
    void fun1()
    {
        cout<<"fun1 in Der"<<endl;
    }
};

int main()
{
    void (Der::*funptr)() = &Base::fun1;
}

Compiler gives an error saying

error: cannot convert 'void (Base::)()' to 'void (Der::)()' in initialization|


1 Answer: 

Because your Der is not derived from Base. Your classes are unrelated. There's no inheritance relationship between them.

If you indeed define your Der as a descendant of Base

class Der : public Base
{
   ...

the code will compile.

The compiler cannot magically guess that you wanted to derive your Der from Base. You are supposed to remember to explicitly tell the compiler about it.