SE Does Not Like Dissent
SE Does Not Like Dissent

Reputation: 1815

Class assignment operator= question

Say I have two classes, in two different headers, called:

class TestA
{
    public:
        int A;
};

class TestB
{
    public:
        int B;
};

And I want to give them both an assignment operator to each other, so it's like:

class TestB; //Prototype of B is insufficient to avoid error with A's assignment

class TestA
{
    public:
        int A;
        const TestA &operator=(const TestB& Copy){A = Copy.B; return *this;} 
};

class TestB
{
    public:
        int B;
        const TestB &operator=(const TestA& Copy){B = Copy.A; return *this;}
};

How do I do the above whilst avoiding the obvious error that will result from calling/using class TestB when it hasn't been defined yet?

Upvotes: 1

Views: 1560

Answers (2)

Daniel
Daniel

Reputation: 6745

If you include both header files in your .cpp file, it should work. Make sure that you have a full definition of both classes in the header files.

Upvotes: 1

Chad
Chad

Reputation: 19022

You cannot have the function definitions in your files as written as that will require a circular dependency.

To solve, forward declare the classes and put their implementation in a separate files.

A's header file:

// A.h

// forward declaration of B, you can now have
// pointers or references to B in this header file
class B;

class A
{
public:
    A& operator=(const B& b);
};

A's implementation file:

// A.cpp
#include "A.h"
#include "B.h"

A& A::operator=(const B& b)
{
   // implementation...
   return *this;
}

Follow the same basic structure for B as well.

Upvotes: 6

Related Questions