views:

107

answers:

5

I've got a class A defined in a separate header file. I want class B to have a reference to a object of class A stored as a variable.

Like this:

File: A.h

class A {
    //Header for class A...
};

File: B.h

#include "A.h"
class B {
    private:
(24)        A &variableName;
    public:
(36)        B(A &varName);
};

When i try to compile it with g++ I get the following error:

B.h:24: error: ‘A’ does not name a type
B.h:36: error: expected `)' before ‘&’ token

Any suggestions on what I'm doing wrong? If it matters, the class A is an abstract class.

EDIT: Some typos in the code

A: 

You appear to try and declare a constructor for class A inside a completely unrelated class B, which is what the compiler is complaining about.

If you want to have default/implicit way of turning a B into an A from the compiler's perspective, you'll need something like

operator A(B const &var);

instead of a constructor declaration.

Timo Geusch
A: 

For all I can see, this code is correct. Check the following please:

  • is A in some namespace?
  • is A a nested class?
  • is A the name of some macro in your code?
  • is A really named A, or is there some typo in your real code?

If none of these work, well then I cannot help you unless you post the real code where the error happens.

Space_C0wb0y
Yeah, that was a typo when I changed the names. It's correct now
Paul
If that is all, then please accept the answer.
Space_C0wb0y
No, that was a typo when I rewrote the code into SO
Paul
Edit: Added list of potential causes.
Space_C0wb0y
A: 

Note that having references as member variables is seldomly a good idea. What does the name B really stand for?

FredOverflow
Why is it a bad idea? There's nothing wrong with having references as member variables.
Peter Alexander
B is a logger. The plan is that it's going to get values from A (which drives a motor connected to the usb) for storage and processing.
Paul
+1  A: 

Does A.h include B.h (directly or indirectly)? If so, then you wouldn't be able to define A before B because of the recursive inclusions. If B needs to be defined in A, use a forward declaration.

Dave
+3  A: 

By me it compiles fine (as expected). I'm guessing A.h isn't being included properly. Is there another file with the same name that gets included instead? Perhaps there are #ifdefs or some such that prevent the definition of A from being seen by the compiler. To check this, I would put some sort of syntax error into A.h and see if the compiler catches it.

Ari
That's it! I've got some #ifndef-s that wasn't correct. Thanks a lot!
Paul
@Paul: thats why it is always better to copy paste the code from editor while asking questions.
Naveen