Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access private members of other template class instances? [duplicate]

This extremely minimal example will fail to compile because A<int> cannot access the private member i in A<double>

template <class T>
class A {
    int i;
  public:
    template <class U>
    void copy_i_from( const A<U> & a ){
        i = a.i;
    }
};

int main(void) {
    A<int> ai;
    A<double> ad;
    ai.copy_i_from(ad);
    return 0;
}

I cannot find the correct way to make those template instances friends.

like image 817
DarioP Avatar asked Oct 17 '14 09:10

DarioP


People also ask

How do you have access to private members of other classes?

Only the member functions or the friend functions are allowed to access the private data members of a class. We can access private method in other class using the virtual function, A virtual function is a member function which is declared within a base class and is re-defined (Overridden) by a derived class.

Can objects of same class access each others private fields?

Private means "private to the class", NOT "private to the object". So two objects of the same class could access each other's private data.

Why do objects of the same class have access to each other's private data?

Objects of the same type have access to one another's private members. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level (this particular instance of a class).

How do you access private members of a class outside the class in C++?

Private and Protected Members in C++ The private data members cannot be accessed from outside the class. They can only be accessed by class or friend functions. All the class members are private by default.


1 Answers

template <class T>
class A {
    template<class U>
    friend class A;
    int i;
  public:
    template <class U>
    void copy_i_from( const A<U> & a ){
        i = a.i;
    }
};

int main(void) {
    A<int> ai;
    A<double> ad;
    ai.copy_i_from(ad);
    return 0;
}
like image 128
101010 Avatar answered Oct 18 '22 23:10

101010