开发者

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);
        }
      };
     }
    }
  1. ChildClass::method() gives a compile error: "'ns1::ParentClass::callback' : cannot access protected member declared in class 'ns1::ParentClass'"
  2. 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..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜