Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - 2 classes 1 file

Tags:

c++

Suppose I want something of this sort, in one .cpp source file:

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

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

Is there anyway of doing this without splitting it into two separate files, and without receiving a compiler error (syntax error on doSomething(B *b))

like image 973
Yuval Adam Avatar asked Mar 24 '09 13:03

Yuval Adam


3 Answers

put at the first line:

class B;
like image 158
Jiri Avatar answered Sep 26 '22 10:09

Jiri


If I remember well, you can 'pre-declare' your class B.

class B; // predeclaration of class B

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

class B
{
    public
      void doSomething(A* a) {}
}

public void A::doSomething(B* b) {}

Then, your class 'A' knows that a class 'B' will exists, although it hasn't been really defined yet.

Forward declaration is indeed the correct term, as mentionned by Evan Teran in the comments.

like image 32
Frederik Gheysels Avatar answered Sep 26 '22 10:09

Frederik Gheysels


forward declare one class before other with

class B;
or
class A;

But still you won't be able to implement

void doSomething(B *b)

using only forward declaration of B. So you have to put definition of doSomething below full class A declaration

like image 20
Mykola Golubyev Avatar answered Sep 24 '22 10:09

Mykola Golubyev