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.
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.
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.
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).
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With