@Mods: maybe this should be moved to the general c++ forum?
@OP:
Rule of thumb: If you can use a forward declaration, use it!
This is because of the way includes work. If you include a file in a header file, it's definitions are available in all other files which include said header file. So, if you have the following piece of code, how should the compiler decide which string class to use?
=========
header1.h
=========
#include <string>
using namespace std;
=========
header2.h
=========
#include <header1.h>
namespace myns
{
class string
{
//... implementation
};
}
using namespace std;
==========
source.cpp
==========
int main(int argc, char** argv)
{
// which string shall the compiler use? std::string or myns::string?
string x = "Hello World!";
cout << x:
return 0;
}
=========
header1.h
=========
#include <string>
using namespace std;
=========
header2.h
=========
#include <header1.h>
namespace myns
{
class string
{
//... implementation
};
}
using namespace std;
==========
source.cpp
==========
int main(int argc, char** argv)
{
// which string shall the compiler use? std::string or myns::string?
string x = "Hello World!";
cout << x:
return 0;
}
To copy to clipboard, switch view to plain text mode
Using forward declaration also improves the time used to build your application as less object files are linked to each other (if I recall correctly right now, had a few beers tonight).
Bookmarks