• Advertisement
Sign in to follow this  

[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.

If you intended to correct an error in the post then please contact us.

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 this post


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement