0
votes

I have the following inheritance structure:

template<unsigned int t>
class Base {
protected:
    int a;
};

template<unsigned int t>
class Derived1 : public Base {

};

template<unsigned int t>
class Derived2 : public Base {

};

What I'd like is to have a Derived1 constructor take a Derived2 object as a argument and then access the protected member 'a' in the Base class.

I've added the following line to the base class:

template<unsigned int u> friend class Derived2;

So that it looks as follows:

template<unsigned int t>
class Base {
protected:
    int a;

template<unsigned int u> friend class Derived2;
};

When I compiled it, I get error C2248: "cannot access protected member declared in class Base"

1

1 Answers

1
votes

If you want to access protected member from Derived1 constructor then you need befriend Derived1 not Derived2.

template<unsigned int t>
class Base {
protected:
    int a;

    template<unsigned int u> friend class Derived1; // here
};

template <unsigned int>
class Derived2;

template<unsigned int t>
class Derived1 : public Base<t> {
public:
    Derived1(Derived2<t>& d2) {
        cout << d2.a << endl;
    }
};

template<unsigned int t>
class Derived2 : public Base<t> {

};

int main() {
    Derived2<1> d2;
    Derived1<1> d1(d2);

    return 0;
}