ChapaPata
ChapaPata

Reputation: 3

Two depending classes c++

I made two classes: ClassA and ClassB that depends with each other. I prototyped ClassB so that the compiler would know there's an available ClassB. ClassA got compiled first then ClassB. So I would assume that the code below would work but the compiler says that ClassB is undefined even though I prototyped it. Now the question is... Why is it giving that error?

#include <iostream>
using namespace std;

class ClassB;

class ClassA{
public:
    ClassA():x(50){}
    void printClassB(ClassB input){
        cout << input.y << endl;
    }

    friend class ClassB;
private:
    int x;
};

class ClassB{
public:
    ClassB(): y(100){}
    void printClassA(ClassA input){
        cout << input.x << endl;
    }

    friend class ClassA;

private:
    int y;

};



int main()
{
    ClassA a;
    ClassB b;

    b.printClassA(a);
    a.printClassB(b);

    cin.ignore();
}

Upvotes: 0

Views: 71

Answers (2)

CiaPan
CiaPan

Reputation: 9570

ClassB is anounced but not defined when you compile ClassA, so in printClassB function compiler doesn't know about ClassB member y. Move the functions out of classes, so they are compiled at the place where both classes are fully defined:

class ClassA{
public:
    ClassA():x(50){}
    void printClassB(ClassB input);

friend class ClassB;
private:
    int x;
};

class ClassB{
public:
    ClassB(): y(100){}
    void printClassA(ClassA input);

friend class ClassA;

private:
    int y;
};

inline void ClassA::printClassB(ClassB input){
    cout << input.y << endl;
}

inline void ClassB::printClassA(ClassA input){
    cout << input.x << endl;
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

For ClassA to use ClassB then ClassB must be fully defined. Since the opposite is also true you can't really do that.

What you can do is use a pointer or reference to ClassB in ClassA, and then use the data from ClassB after you defined it.

Like

class ClassB;

class ClassA{
public:
    void printClassB(ClassB& input);

    ...
};

class ClassB { ... };

void ClassA::printClassB(ClassB& input)
    cout << input.y << endl;
}

Upvotes: 2

Related Questions