Harshad
Harshad

Reputation: 55

Using overloaded assignment operator

I have a template<> class A with a non-default constructor and an overloaded assignment operator:

template<typename T>
class A
{
  public:
  A(T x);
  A(A<T> &parent);
  A<T> & operator=(A<T> &rhs);
};

And a class B, which has A as member, it's own overloaded assignment operator and a getter method for A

class B
{
  public:
  B();
  B& operator=(B &rhs);
  A<int> get_A();

  protected:
  A<int> *member;
};

I have defined the assignment operator and A getter method as follows:

B& B::operator=(B &rhs)
{
  *member = rhs.get_A();
  return *this;
}

A<int> B::get_A()
{
  return *member;
}

The assignment operator doesn't work in this case. Am I missing something here? I get the following error:

B.cpp(92): error: no operator "=" matches these operands
            operand types are: A<int> = A<int>

I also tried

B& B::operator=(B &rhs)
{
  A<int> temp(rhs.get_A());
  *member = temp;
  return *this;
}

in which case I get:

B.cpp(92): error: no instance of constructor "A<T>::A [with T=int]" matches the argument list
            argument types are: (A<int>)
    A<int> temp(rhs.get_A());

Upvotes: 0

Views: 153

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145359

1

regarding

A<T> & operator=(A<T> &rhs);

that should better be

A<T>& operator=(A<T> const& rhs);


2

regarding

B& B::operator=(B &rhs)
{
  *member = B.get_A();
  return *this;
}

that should better be

B& B::operator=(B const& rhs)
{
  *member = rhs.get_A();
  return *this;
}


3

regarding

  B() : member(4);

that should not compile.

it's difficult to say what it should be since member is declared as a pointer, while the value provided is an incompatible integer.


4

regarding

A<int> get_A();

that should better be

A<int> get_A() const;

so that it can be called on a const object.


5

regarding the comment

A is a bit more complicated and contains a linked list. The linked list has to be updated every time an object of A is copied

it does sound a bit fishy that an object has to be updated every time it's copied. the old std::auto_ptr class was almost like that, and it achieved the effect via a hack involving a special proxy reference class. it's possible that your objects are not really copyable but just movable, in which case, don't use the copy assignment operator for whatever the operation really is, but use e.g. an ordinary named member function.

Upvotes: 3

Related Questions