5

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))

RiaD
  • 46,822
  • 11
  • 79
  • 123
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395

8 Answers8

22

put at the first line:

class B;
Jiri
  • 16,425
  • 6
  • 52
  • 68
12

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.

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
4

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

Mykola Golubyev
  • 57,943
  • 15
  • 89
  • 102
3

Yes. You need a forward declaration:

class B; // add this line before A's declaration

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

class B {
    public:
        void doSomething(A *a) {};
};
Mr Fooz
  • 109,094
  • 6
  • 73
  • 101
3

The C++ FAQ Lite answers this question and others. I'd seriously considering reading that thing end to end, or getting the book and doing the same.

Brian
  • 25,523
  • 18
  • 82
  • 173
1

You can try a forward declaration like

class B;
class A {
  void Method( B* );
};
class B{
};

but you will only be able to declare pointer and reference variables for B then. If you want more (like a method that dereferences B* variable) you can provide a declaration only and define methods later in the same file - at the point where both classes declaration is already available.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
1

You need to forward declare B.

class B; 

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

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

(And BTW, you don't need the semi-colons after the member function curly braces. :) )

Brian Neal
  • 31,821
  • 7
  • 55
  • 59
0

Add another declaration of B before A:

class B;

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

class B {
    public:
        void doSomething(A *a) {};
};
Jay Michaud
  • 405
  • 3
  • 18