tags:

views:

42

answers:

4

Hi, could anyone please help to resolve this (the problem is persistent under both GCC and VC++).

template <class T> class A{  
protected:  
    T a;  
public:  
    A(int aa=0){a=aa;}  
    virtual ~A(){}  
    virtual void plus(A const *AA){a=a+AA.a;}  
};  

class B:public A<int>{  
public:     
    B(int bb=0):A<int>(bb){}  
    virtual ~B(){}  
    void plus(A<int> const *AA){a=a+AA->a;} //<--PROBLEM: I can access a but not AA->A?  
};  
+3  A: 

This is to be expected.

An instance of B has no right poking around in the internals of an arbitrary A; it has a right only to access the A part of (other) Bs. That's what the protected keyword means.

UncleBens
thanks -- while i was waiting for the answer I stripped down the code off templates and the problem became more apparent. so, the "only" (reasonable) resolution is declare B as friend?
Yuriy
@Yuriy: Basically this is indicating a design problem. But yes, you can work around making B a friend.
UncleBens
@Yuriy: No need to use friend. See my response.
Eric Fortin
could you suggest a better design (if it does not require too much effort/typing, of course). what I want to do is: declare class A<typename T>, derive from it specialized B that would re-implement some of A's behavior but more efficiently?
Yuriy
Thanks again -- I just realized what I need to do:)
Yuriy
A: 

This is not a problem with compilers but standard conformant behaviour. You can access protected members of a base class only through this (implicitly or explicitely).

usta
A: 

This should look like:

class B:public A<int>{  
public:     
    B(int bb=0):A<int>(bb){}  
    virtual ~B(){}  
    void plus(A<int> const *AA){this->A::plus(AA);}
};

No need to reimplement the plus function in the derived class if it's doing the same.

Eric Fortin
Thanks! B::plus is to be customized, so is not doing the same (only in the example above it does)
Yuriy
+2  A: 

"UncleBens" has already answered your main question, but some details...

First:

virtual void plus(A const *AA){a=a+AA.a;}  

Since AA is a pointer you can't do AA.a... ;-)

Second, be aware that member pointers do not generally honor accessibility. Using just implicit conversions you can gain access to a base class' protected stuff. Member pointers are to accessibility about the same as what goto is to flow control.

Cheers & hth.,

– Alf

Alf P. Steinbach