[c++] Precompiled headers - No need to forward declare?

This topic is 3025 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

If I use a precompiled header, I need include it in all my source files (*.cpp), but not in my header files (*.h). Now, lets consider this scenario: In my precompiled header (common.h) I have included <string>, because I'm going to be using std::string objects all over my project. Lets say I want to add a class named Object to my project that has a std::string member. This is what I would do: Object.h
#ifndef OBJECT_H
#define OBJECT_H

class Object
{
public:
Object(const std::string& _id);
private:
std::string id;
};

#endif


Object.cpp
#include "common.h" //or stdafx.h if you prefer...

#include "Object.h"

Object::Object(const std::string& _id): id(_id) {}


This works, however what is strange to me about this is that Object.h uses std::string without any knowledge of it. Is this standard behavior? The problem is that you cannot just forward declare std::string, so you'd have to include <string> again in Object.h. Wouldn't that defeat the purpose of having it in the precompilded header?

Share on other sites
Object.h isn't compiled, only Object.cpp which includes common.h before Object.h.

Share on other sites
Indeed, good thing I chose to play around with precompiled headers, because I obviously had a wrong mental model of how includes work.