Mike
Mike

Reputation: 477

How to overload operator =

I am trying to overload the assignment operator as a member function to take a string as an argument and assigns its value to A, the current object. I posted the errors in the comments below.

Can someone tell me what I'm doing wrong? I think it has something to do with the parameters, and probably the code inside the definition.

I am not sure if I declared it correctly, but I declared it like this:

WORD operator=(const string& other);

And I defined it like this:

WORD WORD::operator=(const string& other) //<---not sure if I did the parameters Correctly
{
(*this) = other;
return (*this);
}

Here is the entire file if it helps:

#include <iostream>

using namespace std;

#pragma once

class alpha_numeric //node
{
   public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};

class WORD
{
   public:
      WORD() : front(0) {length=0;}; //front of list initially set to Null
      WORD(const WORD& other);
      bool IsEmpty();
      int Length();
      void Insert(WORD bword, int position);
      WORD operator=(const string& other); 

   private:
      alpha_numeric *front; //points to the front node of a list
      int length;
};

WORD WORD::operator=(const string& other) //<---not sure if I did the parameters Correctly
{
      (*this) = other;
      return (*this);
}

Upvotes: 0

Views: 231

Answers (2)

Julien Lebot
Julien Lebot

Reputation: 3092

Ok 2 things:

First you are missing the definition of your copy constructor, so that's not compiling. Try this inside your class (only partial implementation shown):

WORD(const WORD& other)
: length(other.length)
{
    // Construct me !
}

Second, your assignment operator is correct, but recursive on all control path. E.g. it calls itself indefinitely. Your probably want to assign members inside the method (again, only partial implementation shown):

WORD WORD::operator=(const string& other)
{
    // Only copy the length, the rest is to be filled
    this.length = other.length;
    return (*this);
}

Lastly, as others have pointed out, you have multiple definitions of the same symbols inside your executable. To fix that you will have to make sure your header is included only once (the #pragma once should take care of that) but also move all implementation details off the header file to the source file. e.g. move the definition of WORD WORD::operator=(const string& other) to the CPP file.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272752

The error message is from the linker; it's telling you that it's found multiple definitions of the same function. This is because you've defined the function in the header file, which has been included into multiple source files, therefore you've ended up with multiple definitions of the function.

Upvotes: 1

Related Questions