Sign in to follow this  
kloffy

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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this