Derived class can't see parent class properly
I'm seeing two problems in a setup like this:
namespace ns1
{
class ParentClass
{
protected:
void callback();
};
}
namespace ns1
{
namespace ns2
{
开发者_如何学Go class ChildClass : public ParentClass
{
public:
void method()
{
registerCallback(&ParentClass::callback);
}
};
}
}
- ChildClass::method() gives a compile error: "'ns1::ParentClass::callback' : cannot access protected member declared in class 'ns1::ParentClass'"
ParentClass *pObj = new ChildClass()
gives an error, that it can't do the conversion without a cast. C++ can down-cast happily, no?
Change:
registerCallback(&ParentClass::callback);
...to:
registerCallback(&ChildClass::callback);
The reason is because &ParentClass::callback is a fully-qualified typename, not resolved from the context of ChildClass but from global context. In other words, it is the same problem as this:
class Thingy
{
protected:
virtual int Foo() {};
};
int main()
{
Thingy t;
t.Foo();
return 0;
}
A derived class can only access protected members of a base class if that base class instance is - and is accessed via - a derived class instance. A derived class doesn't have access to protected members of other types of base class.
Edit: When forming a pointer to a member, a protected member of a base class may be used but the name used to scope the member name must be a derived class name and not the base class name so this 'cannot access' error is correct.
For point 2., with using ns1::ParentClass;
and a using ns1::ns2::ChildClass;
at the outer scope after the complete declaration of ChildClass
, I don't get any error with your statement.
Declare function as public.
Make sure that base class has virtual destructor..
精彩评论