Permission problem on a derived private method from public method

problem:
Is there a good explanation why compilation tags error for the call to
AA.method(). It is public in the base class. If cast to baseclass,
then compiler says it's ok.

class  A 


public
    A() 
{} 
    virtual 
~A() {} 
    virtual 
void method(void{ std::cout << "A::method" <<std::endl; } 
}
; //  A 
class  AA :  public  A 
public
    AA() 
{} 
    virtual 
~AA() {} 
private
    virtual 
void method(void
       A::method(); 
       std::cout 
<< "AA::method" << std::endl; 
    }
 
}
; //  A 
int  main() 

    AA obj; 
    A
* p = &obj; 
    p
->method(); 
    
//((A&)obj).method(); 
    obj.method();                  // ERROR: 
 }


gcc -o drvd drvd.cpp -lstdc++ -lm
drvd.cpp: In function `int main()':
drvd.cpp:26: error: `virtual void AA::method()' is private
drvd.cpp:46: error: within this context
http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/7ae23191ff4de6a9/4560e82948e9b91e#4560e82948e9b91e

solution:
     Above ,it seems as if it is a paradox !
     why in devived class,function method() is declared as a private memeber,still in the way
      A* p = &obj; 
    p
->method(); 
   it is right!
  The phenomena is explained in the Inside the C++ object model!
  In fact,p->method() is checked in two phases!
 At complie time,p->method()
 According to p type,check method()'s access level and method()'s validity,such as membership!
so p->method() is right!
At run time,
p->method() is called in polymorphism way according to p's RTTI information!
extending:
Although it looks strange,maybe we can employ it!
for example:
class A{
public:
virtual void method()=0;
}
class AA:public A{
private:
virtual void method(){
...
}
};
Obviously,
A is interface and AA is a implemention!
In the way,if you use AA directly,
it will result in error,so prevent any subclass's use!
A is the only entry!
It may be helpful in some library's device!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值