Commuze
Commuze

Reputation: 35

(C++) Use other class' object as parameter in a class when two classes use each other's object

My title sounds a little weird... But my question is...

class A{
public:
    doSomething(B & b);
}

class B{
public:
    doSomething(A & a);
}

is this not supposed to work??

I get errors saying function does not take 1 parameter because the identifier (classes) is undefined...

Upvotes: 1

Views: 154

Answers (2)

Barath Ravikumar
Barath Ravikumar

Reputation: 5836

class A{
public:
    doSomething(B & b);
};

is not ok , because the compiler is yet to know what B is , which is defined latter.

Compiler Always works from a top-down approach , so it must have seen a class (either declared or defined) , before it is being used elsewhere , so your code should be

class A; // Not reqd in your case , but develop a good programming practice of using forward declaration in such situations
class B; // Now class A knows there is asnothed class called B , even though it is defined much later , this is known as forward declaration

class A{
public:
    doSomething(B & b);
}

class B{
public:
    doSomething(A & a);
}

Upvotes: 0

Captain Obvlious
Captain Obvlious

Reputation: 20063

A type needs to be declared before it can be used. Since you have an interdependency between classes you need to use a forward declaration.

class B; // Forward declaration so that B can be used by reference and pointer
         // but NOT by value.

class A{ public: doSomething(B & b); }

class B{ public: doSomething(A & a); }

Note that this is generally considered a very bad design and should be avoided if possible.

Upvotes: 3

Related Questions