1

Foo.h

class Foo{
private:
    void printSpecialBar(Bar b);//syntax error: Identifier Bar

Foo.cpp

#include "Bar.h"

void Foo::printSpecialBar(Bar b)
{
    //code goes here
}

Bar has the default constructor and one that takes two int's.

What is the problem with the syntax error? I tried using the scope resuloution operator Bar::Bar b but it didn't fix it.

5
  • 1
    You have to include Bar.h in Foo.h Commented Jan 28, 2014 at 3:16
  • 1
    @awesomeyi is that in addition to including it in Foo.cpp? Commented Jan 28, 2014 at 3:18
  • 1
    Since you are using Bar inside one of Foo's member function declarations, you must tell the compiler what it is. Otherwise, the compiler thinks that you made a typo. Forward-declaring Bar with class Bar; would give compiler enough information to compile your program, as long as the declaration precedes the point where Bar is first used. Commented Jan 28, 2014 at 3:22
  • 1
    @awesomeyi Can certainly include it, and it would fix the problem. However, it is not strictly required here: a forward declaration would be enough. Commented Jan 28, 2014 at 3:26
  • @awesomeyi and where possible, a forward declaration is always preferred to including the full type definition. Generating chains of .h files can substantially increase compile times and sometimes lead to errors. Commented Jan 28, 2014 at 4:21

2 Answers 2

1

A typical practice would be to put

class Bar;

in Foo.h, before any reference to Bar class, and include the actual class like

#include "Bar.h"

in Foo.cpp.

Sign up to request clarification or add additional context in comments.

1 Comment

Well it really has nothing to do with #pragma once. So either position would be okay.
0

Since Foo.h references Bar, either use a forward declaration or #include "Bar.h" in Foo.h

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.