steveo225
steveo225

Reputation: 11892

Accessing private member variables from a templated class assignment operator

I have a container class that is templatized. I am overloading the assignment operator such that derived types can also be assigned.

My problem is, when the type is not the same, I cannot access the private members of the container class. What is the best approach to gaining access? The member variables cannot be made accessible through public getters. Thanks!

Example Code:

// Note: var is private

template <class T>
Container<T>& Container<T>::operator=(const Container<T>& rhs) {
   if(*this != rhs) var = rhs.var; // works for same type
   return *this;
}

template <class T>
template <typename U>
Container<T>& Container<T>::operator=(const Container<U>& rhs) {
   if(*this != rhs) var = rhs.var; // does NOT work for different types
   return *this;
}

Upvotes: 20

Views: 5057

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361622

Since you want to access private members of template class instantiated with different types, you've to make other templates as friend of the template class as:

template <class T>
class Container
{
      template<class U> 
      friend class Container;

};

Note that if T and U are different types, then Container<T> and Container<U> are two completely different classes; one cannot access private members of other if you don't make friend one of other.

Also note that in the above code all instantiations of the class template are friend of each other. That is, if you instantiate it with char, int, short, then

  • Container<int> will be friend of both Container<char> and Container<short>.
  • Container<char> will be friend of both Container<int> and Container<short>.
  • Container<short> will be friend of both Container<int> and Container<char>.

The interesting phrase here is : "friend of each other". Usually this doesn't happen. For example, if you have a class like this:

class A
{
   friend class B;
};

Then here only B is friend of A. A is NOT friend of B. They're NOT "friend of each other". B can access private members of A, but A cannot access private members of B. That is the difference between this class and the template class above.

Upvotes: 22

Luchian Grigore
Luchian Grigore

Reputation: 258618

The first operator works because access is class-scope and not object-scope. That means you can access private members across instances of the same class.

To access a private member from a different class without using getters or setters you need to make your class friends with the other class.

Other ways involve hacks, accessing memory directly and are not portable.

Upvotes: 1

Related Questions