Inheritance and protected attribute

356 views Asked by At

I'm writing the following structure :

class F {
protected:
    F* i;
public:
    F(){i=NULL;}
    virtual F* clone()const=0;
    virtual double operator()(double x)const=0; 
    virtual F* derivative()const=0;
    virtual double inverse(double y)const=0; 
    virtual ~F(){}

};

class T : public F{
    string n;
public:
    T(string n_);
    F* clone()const;
    double operator()(double x)const;
    F* derivative()const;
    double inverse(double y)const;
    ~T(){}
};

I'm writing method 'T::derivative' right now. My two first lines are :

F* T::derivative()const
{
    F* deriv;
    deriv->i=clone();

}

F* T::clone()const
{
    return new T(n);
}

but Xcode tells me for the second line in 'T::derivative' that 'i' is a protected member of 'F. I can't understand why I can't have access to it when I'm in 'T', which inherits from 'F'.

2

There are 2 answers

0
Mike Seymour On

A member of class T can only access protected members of objects of class T (including the currect object), not arbitrary objects of class F or other subtypes.

Whatever deriv is supposed to be (at the moment, it's an uninitialised pointer, so you'd have big problems even if the code did compile), it will have to be T* (or a subtype of T) in order to access i through it. Either that, or i will need to be more widely accessible.

1
Ali Kazmi On

Since protected members are only accesible to (Sub Class ) T (here) (since only derievedd class from base F). To access i (protected member) instantiate T and use i . Here change this to

F* deriv;
T* deriv;

and you have your error disappeared.