2

I have this 2 separated class and i cant fix this compiler problem:

In file included from classA.cpp:2:0: classB.h:6:10: error: 'string' in namespace 'std' does not name a type std::string str; ^

In file included from classA.cpp:3:0: classA.h:6:25: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 classB *ptr_b = new classB;

There is the classA.h:

#ifndef CLASSA_H
#define CLASSA_H

class classA {
private:
    classB *ptr_b = new classB;
public:
    classA();
};

#endif /* CLASSA_H */

classA.cpp:

#include "classB.h"
#include "classA.h"

classA::classA() {
}

classB.h:

#ifndef CLASSB_H
#define CLASSB_H

class classB {
private:
    std::string str;
public:
    classB();

};

#endif /* CLASSB_H */

classB.cpp:

#include <string>
#include "classB.h"

classB::classB() {
}

I apreciate all the help you can give. I don´t know how to fix this and I'm going crazy.

Thanks for reading.

5
  • 1
    You should #include <string> from classB.h. As it stands, <string> is included by classB.cpp but not classA.cpp (which also includes classB.h). Commented May 17, 2016 at 23:02
  • if i include <string> in classB.h i can delete on classB.cpp? Commented May 17, 2016 at 23:04
  • Yes, you can remove it from classB.cpp if it's in classB.h. Commented May 17, 2016 at 23:04
  • 2
    @BlackB0ltz you should keep it in classB.cpp as well if that file uses std::string, please don't depend on indirect includes as they are fragile. If you don't use string in classB.cpp feel free to remove it. Commented May 17, 2016 at 23:06
  • So, if i use the string in classB.cpp, I have to include <string> in classB.h and classB.cpp? I'm a bit confused. Commented May 17, 2016 at 23:26

1 Answer 1

4

You need #include <string> in classB.h. Right now classA.cpp includes classB.h with no prior #include <string> anywhere, so the included reference to std::string in classB.h causes an error.

In general, if a name is used in a header foo.h, you should include the header bar.h that declares the name in foo.h, or forward-declare the name in foo.h. Otherwise everyone else who includes foo.h will need to remember to make sure bar.h gets included first.

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

1 Comment

Thanks for the help.

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.