It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a trouble with finding answer for my questions (Q), so I registered here to ask you guys how it really works (or don't works) ;)
I am writing in c++, in Visual Studio 2012, but still don't really know how it is with #includes, namespaces etc. in header files. Do I even need to use them?
(Q1): Let's say I have one .cpp file and few .h files, which are using, for example: vectors, things from <algorithm>, <ctime> and some other libraries, but I do not write #include <something> in header files, only in .cpp. Is it correct? Or should I include everything I use in every header?
Usually everything works for me, I can even say it always "works", because I don't have too much experience yet and I was usually containing everything in one .cpp and 1 or 2 headers with some void functions. But don't know if it works because it should, or because, for example, mu compiler allows that and in some issues it can cause errors.
(Q2): Now a thing about using namespace std;
In some cases functions in .h files works without it, but sometimes not. For example, the voids that are working (just simple voids for merge-sort):
#ifndef LISTA_1_H
#define LISTA_1_H
#include "Lista_0_Zadanie_1.h"
void MERGE(vector<double> &A, int p, int q, int r)
{
int i = p;
int j = q+1;
int lenght = r - p + 1;
int k=0;
vector<double> merged;
merged.assign (lenght,0);
while((i<=q)&&(j<=r))
{
if(A[i] <= A[j])
{
merged[k]=A[i];
++i;
}
else
{
merged[k]=A[j];
++j;
}
k++;
}
if(j<=r)
{
while(j<=r)
{
merged[k]=A[j];
++j;
++k;
}
}
if(i<=q)
{
while(i<=q)
{
merged[k]=A[i];
++i;
++k;
}
}
for (i=0;i<lenght;++i)
A[p+i]=merged[i];
}
void MERGESORT(vector<double> &A, int k, int l)
{
if(k<l)
{
int m = (k+l)/2;
//int mp = m+1;
// cout << "koza"<<endl;
MERGESORT(A,k,m);
MERGESORT(A,m+1,l);
MERGE(A,k,m,l);
}
}
void TRIPLE_MERGESORT(vector<double> &A, int k, int l)
{
if(k<l)
{
int one_third = (l-k)/3;
int two_third = 2*(l-k)/3; // k < k+one_third < k+two_third < l
TRIPLE_MERGESORT(A,k,k+one_third);
TRIPLE_MERGESORT(A,k+one_third+1,k+two_third);
TRIPLE_MERGESORT(A,k+two_third+1,l);
MERGE(A,k,k+one_third,k+two_third);
MERGE(A,k,k+two_third,l);
}
}
void INSERT_MERGESORT (vector<double> &A, int k, int l)
{
if(l<19) // l=n-1, więc n<20 <=> l < 19
{
double y;
int i,j;
for(i=0; i<l+1; ++i)
{
y = A[i];
j = i-1;
while((j>=0) && (A[j]>y) )
{
A[j+1] = A[j];
--j;
}
A[j+1]=y;
}
}
else
MERGESORT(A,k,l);
}
#endif
... and in some cases it does not work, if I do not write "using namespace std;" or add " std:: " in correct place (here before vectors), it does not work:
#ifndef SCHEMAT_HORNERA_H
#define SCHEMAT_HORNERA_H
//using namespace std;
void HORNER( int n, double z0, double p_z0, vector<double> a, vector<double> &B)
{
B[n] = a[n];
for(int k = n-1; k>=0; --k)
{
B[k] = a[k] + z0*B[k+1];
}
}
#endif
So here's my question: Should I always use "std::" or "using namespace std"?
If yes, why are my files until now "working"? Because in some cases VS allows for that, while it is not correct and some compilers and not allow for this?
Q1) Whether or not you need to #include a header with a full definition depends on if you need a full definition, or if just a forward-declare will do. In the case of needing just a forward-declaration, all you need to tell the compiler is the name of something. An example is if you need a pointer-to-something:
// fw-decl Foo
class Foo;
// define Gizmo
class Gizmo
{
public:
void DoIt();
Foo* mFoo; // just need a pointer, so don't need a full definition of foo
};
Later you will need a full definition if you actually use the Foo object, as with:
#include "foo.h"
#include "gizmo.h"
void Foo::DoIt()
{
mFoo->DoSomething(); // now we need a full definition
}
On the other hand, if the compiler needs to know for example how big Foo is, then you need a full definition.
#include "foo.h"
class Gizmo
{
public:
Foo mFoo; // need a full definition here
};
As a general rule of thumb, it is best to provide full definitions only when necesarry, so as to keep compilation times as quick as possible.
Q2) Simplified rule-of-thumb: never using namespace std. If you simply follow this rule of thumb without ever thinking about it, you will never have problems with namespace collisions, polluting the global namespace, or other nastiness.
Of course, this rule of thumb is a little over-simplified for those who actually think for a living, so here's a slightly better one:
1) Never using namespace in a header
2) Never using namespace in a source file unless it's your own namespace you're implementing.
Rules of thumb can be overly restrictive, and this is no exception, but it will get you on your way without venturing too far in to a landmine. The problem with using anmespace is it brings whatever is in that namespace in to global scope. Suppose you have your own header file:
mystring.h
namespace MyString
{
class string
{
// ...
};
}
...and then in the source file:
#include "mystring.h"
#include <string>
using namespace MyString;
using namespace std;
string s; // OOPS: which "string" is this? MyString::string, or std::string?
This ambiguity is obvious here, but int he real world it can be much less obvious, and result in some very hard-to-detect bugs.
(Q1) It is important to remember what an include declaration actually does. Basically it is nothing more than a simple copy/paste of the entire file which is being included in the new file.
Since header files are included in many places, it is generally frowned upon to have many unnecessary includes in .h files (unless using templates). In general, do not include in a header file when a forward declaration will suffice.
In the .cpp file, include ALL files necessary so that the program can compile.
Because you are using visual studio, you must be careful because it is very lenient on including files from the standard library that you actually forgot to include, and you may experience problems compiling on other systems.
(Q2) In a header file you should not have a "using" statement. Remember that the include statement is a simple copy/paste; so for that reason if you have a using statement it will be included in the new file as well.
In .h files you should always use std::vector, std::set, etc.
In .cpp files, it is ok to have using namespace std, using std::vector, etc.
(Sidebar) Related to your code, you should split it up into header files and cpp files. Do not have the definition in the .h file, only the declaration. Make a .cpp file and define the algorithm in there. Also do not have define guards in a .cpp file. Never include a .cpp file!
Related
This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
Ok so I'm still getting used to C++ again, so this error may seem simple. I'm attempting to create a simple class with a three member functions (I'm only trying to call one of them in this). So I create the class, instantiate an object, then attempt to call the function using that object and this error comes up:
Code.cpp:(.text+0x15): undefined reference to `Code::genCode()'
I've double checked to see if it was an error with the function itself, but that is not the case. I've seen others post about this issue but there seems to be a multitude of situations and solutions. Anyway here's the code:
#include <vector>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <list>
using namespace std;
class Code {
public:
int genCode();
int checkCorrect();
int checkIncorrect();
};
int main()
{
Code c1;
c1.genCode();
}
////////////////FUNCTIONS/////////////////////////
int genCode()
{
vector <int> newcode;
srand(time(NULL));
for(int i = 0; i < 9; i++){
int x;
x = (rand() % 6);
if (find(newcode.begin(),newcode.end(), x) == newcode.end())
{
newcode.push_back(x);
}
}
if (newcode.size() > 4)
{
newcode.pop_back();
}
for(int i = 0; i < 4; i++)
{
return newcode[i];
}
}
int checkCorrect()
{
}
int checkIncorrect()
{
}
you need to put class name before method name
the format is
'returnType Classname::methodname
{
codes
}'
int code::genCode()
{
//codes
}
or you also possible to write code in class
Change the implementation of the methods of your class to the following:
int Code::genCode()
{
...
}
int Code::checkCorrect()
{
...
}
int Code::checkIncorrect()
{
...
}
You are defining the functions outside the class. Put them inside the class, then you don't need to declare them inside the class. Directly define them.
#include <vector>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <list>
using namespace std;
class Code {
public:
////////////////FUNCTIONS/////////////////////////
int genCode()
{
cout << "Inside genCode. Just for Debugging purpose." << endl;
vector <int> newcode;
srand(time(NULL));
for(int i = 0; i < 9; i++){
int x;
x = (rand() % 6);
if (find(newcode.begin(),newcode.end(), x) == newcode.end())
{
newcode.push_back(x);
}
}
if (newcode.size() > 4)
{
newcode.pop_back();
}
for(int i = 0; i < 4; i++)
{
return newcode[i];
}
}
int checkCorrect()
{
}
int checkIncorrect()
{
}
};
int main()
{
Code c1;
c1.genCode();
}
Otput:
Inside genCode. Just for Debugging purpose.
The function
int genCode()
Is what's called a free function. It is not bound to a class.
In order for the compiler to know that genCode is part of a class, you have to tell it by explicitly stating the namespace to which genCode belongs.
int Code::genCode()
However since it appears code Code is entirely contained within one file, following CodeRunner's advice will lead to a cleaner implementation.
But why would anyone want to got the trouble of splitting everything up?
Separating the class definition from the method implementations allows you place the class definition into one file, the 'h header file, and the methods in an implementation file, usually a .cpp file. The header file is then shared with users of the Code object and the implementation file can be compiled into a library and hidden from the callers view.
There are a number of reasons to do this, but most of them have to do with creating pre-compiled libraries and using them to reduce build times.
With a library, you build the library once, and then compile the rest of the code that uses the library over and over until you get it right. Can you imagine how long it would take to build a program if you had to rebuild the C++ standard library every time you fixed a bug and wanted to test?
Had a job like that once. Had to spend four hours compiling third party network code every time I made a fix because the company's paranoid build system rebuilt everything every time. Off by one error? 4 hours. Need to add a debug line? 4 hours. You could make and test three changes a day. Sure, you can batch up a bunch of fixes, but if one failed spectacularly and broke the system, which one was it? Sooner or later you're reduced to a crawl, making tweaks, building, testing, profiling one at a time. Fortunately I was working on contract and paid by the hour.
Another good example is you can have one library that supports Windows and other libraries supporting QNX and other operating systems. All use the same header and the user can write a program that, in theory, will operate on all supported platforms simply by recompiling the user's code. It's never quite that clean, but one can dream.
The library can even be replaced with an updated library without requiring changes or compilation of the user's code and different variants of the library can exist for different needs. A debug version with extra logging, for example.
Perhaps the implementation is not intended for public eyes. The users get to see the header and call functions in the library, but no more.
I'm making my first attempt at unit testing in C++, and I haven't used C++ in a number of years (I'm mainly a C# coder at the moment). It seems like I'm making a right pig's ear of it - I hope someone can steer me back onto the righteous path. I'm just getting started here and would really like to be implementing these tests using the best practice possible, so any and all comments are welcome, even though I'm most concerned with my linker error at present.
So, I have an overall solution "Technorabble", with sub-projects "CalibrationTool" and "CalibrationToolUnitTests".
CalibrationTool has a MathUtils.h file:
#ifndef __math_utils__
#define __math_utils__
#include "stdafx.h"
#include <vector>
namespace Technorabble
{
namespace CalibrationTool
{
double GetDoubleVectorAverage(std::vector<double> v)
{
double cumulativeValue = 0;
for(std::vector<double>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
cumulativeValue += *iter;
}
return cumulativeValue / v.size();
}
}; // end namespace CalibrationTool
}; // end namespace Technorabble
#endif // !__math_utils__
(But no .cpp file as I was having all kinds of (somewhat similar) issues getting my template function working - so I ended up defining that inline).
Moving on to the Unit Tests project, I have a main.cpp:
#include "MathUtilsTest.h"
void RunMathUtilsTests();
int main()
{
RunMathUtilsTests();
// Other class tests will go here when I have things to test
}
void RunMathUtilsTests()
{
MathUtilsTest* mathUtilsTest = new MathUtilsTest();
mathUtilsTest->RunTests();
delete mathUtilsTest;
}
Finally, the header and cpp for the MathUtilsTest class, again, fairly simple:
.h:
#ifndef __MATH_UTILS_TEST__
#define __MATH_UTILS_TEST__
#include "CalibrationToolUnitTestsLogging.h"
#include "..\CalibrationTool\MathUtils.h"
class MathUtilsTest
{
public:
MathUtilsTest();
~MathUtilsTest();
bool RunTests();
private:
bool GetDoubleVectorAverageTest();
}; // end class MathUtilsTest
#endif
.cpp:
#include "MathUtilsTest.h"
#include <sstream>
bool MathUtilsTest::RunTests()
{
return GetDoubleVectorAverageTest();
}
MathUtilsTest::~MathUtilsTest()
{
}
MathUtilsTest::MathUtilsTest()
{
}
bool MathUtilsTest::GetDoubleVectorAverageTest()
{
bool passed = true;
std::vector<double> values;
for (int i = 1; i < 23; i++)
{
values.push_back(i);
}
// vector becomes: 1, 2, 3, 4, .....20, 21, 22. Average is 11.5
double expectedAverage = 11.5;
double calculatedAverage = Technorabble::CalibrationTool::GetDoubleVectorAverage(values);
if (calculatedAverage != expectedAverage)
{
std::ostringstream s;
s << calculatedAverage;
std::string avgString = s.str();
CalibrationToolUnitTestsLogging::Write("Failed MathUtilsTest.GetDoubleVectorAverageTest: " + avgString);
passed = false;
}
else
{
CalibrationToolUnitTestsLogging::Write("Passed MathUtilsTest.GetDoubleVectorAverageTest");
}
return passed;
}
This all seemed fine to me, I'm protecting my header with #ifndef, etc. But I'm still getting the following errors:
1) error LNK1169: one or more multiply defined symbols found
2) error LNK2005: "double __cdecl Technorabble::CalibrationTool::GetDoubleVectorAverage(class std::vector >)" (?GetDoubleVectorAverage#CalibrationTool#Technorabble##YANV?$vector#NV?$allocator#N#std###std###Z) already defined in main.obj C:_SVN\Technorabble\Windows Software\CalibrationToolUnitTests\MathUtilsTest.obj
How can this be? Can anyone spot where it's going wrong?
Functions defined in headers should be marked as inline:
inline double GetDoubleVectorAverage(std::vector<double> v)
{
}
If it's longer than a couple of lines, consider moving it to an implementation file.
pragmas or include guards don't protect against multiple definitions.
Note that you should pass v by const reference rather than by-value.
You are defining a function GetDoubleVectorAverage in a header. This means that it will be defined in every translation unit (i.e. every source file) that includes that header. If your program contains more than one such translation unit, then you'll have more than one definition - which isn't allowed.
Solutions are:
Add inline to the function definition, to relax this rule and allow multiple identical definitions; or
Move the function definition into a source file, and only declare it in the header.
I'm protecting my header with #ifndef
That only prevents the header from being included more than once within the same translation unit. It doesn't prevent inclusion from more than one unit.
Also, you shouldn't use a reserved name like __math_utils__ as a header guard, even if the internet is littered with examples of dodgy code doing that.
I was having all kinds of (somewhat similar) issues getting my template function working
Templates usually need to be defined in header files, to make the definition available at the point of use. Function templates are implicitly inline, but normal functions (like this one) aren't.
Is there any difference between wrapping both header and cpp file contents in a namespace or wrapping just the header contents and then doing using namespace in the cpp file?
By difference I mean any sort performance penalty or slightly different semantics that can cause problems or anything I need to be aware of.
Example:
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
namespace X
{
void Foo::TheFunc()
{
return;
}
}
VS
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
using namespace X;
{
void Foo::TheFunc()
{
return;
}
}
If there is no difference what is the preferred form and why?
The difference in "namespace X" to "using namespace X" is in the first one any new declarations will be under the name space while in the second one it won't.
In your example there are no new declaration - so no difference hence no preferred way.
Namespace is just a way to mangle function signature so that they will not conflict. Some prefer the first way and other prefer the second version. Both versions do not have any effect on compile time performance. Note that namespaces are just a compile time entity.
The only problem that arises with using namespace is when we have same nested namespace names (i.e) X::X::Foo. Doing that creates more confusion with or without using keyword.
There's no performance penalties, since the resulting could would be the same, but putting your Foo into namespace implicitly introduces ambiguity in case you have Foos in different namespaces. You can get your code fubar, indeed. I'd recommend avoiding using using for this purpose.
And you have a stray { after using namespace ;-)
If you're attempting to use variables from one to the other, then I'd recommend externalizing them, then initializing them in the source file like so:
// [.hh]
namespace example
{
extern int a, b, c;
}
// [.cc]
// Include your header, then init the vars:
namespace example
{
int a, b, c;
}
// Then in the function below, you can init them as what you want:
void reference
{
example::a = 0;
}
If the second one compiles as well, there should be no differences. Namespaces are processed in compile-time and should not affect the runtime actions.
But for design issues, second is horrible. Even if it compiles (not sure), it makes no sense at all.
The Foo::TheFunc() is not in the correct namespacein the VS-case. Use 'void X::Foo::TheFunc() {}' to implement the function in the correct namespace (X).
In case if you do wrap only the .h content you have to write using namespace ... in cpp file otherwise you every time working on the valid namespace. Normally you wrap both .cpp and .h files otherwise you are in risk to use objects from another namespace which may generate a lot of problems.
I think right thing to do here is to use namespace for scoping.
namespace catagory
{
enum status
{
none,
active,
paused
}
};
void func()
{
catagory::status status;
status = category::active;
}
Or you can do the following:
// asdf.h
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
Then
// asdf.cpp
#include "asdf.h"
void X::Foo::TheFunc()
{
return;
}
The biggest problem I seem to run into when coding in c++ is the fact that you must declare a class before you can reference it. Say I have two header file like this...
Header1.h
#include "Header2.h"
#include <deque>
#include <string>
#include <iostream>
using namespace std;
class HelloPackage;
class Hello
{
public:
string Message;
HelloPackage * Package;
Hello():Message("")
{
}
Hello(string message, HelloPackage * pack)
{
Message = message;
Package = pack;
}
void Execute()
{
cout << Message << endl;
//HelloPackage->NothingReally doesn't exist.
//this is the issue essentially
Package->NothingReally(8);
}
};
Header2.h
#include "Header1.h"
#include <deque>
#include <string>
#include <iostream>
using namespace std;
class HelloPackage
{
public:
deque<Hello> Hellos;
HelloPackage()
{
Hellos = deque<Hello>();
}
int AddHello(string Message)
{
Hellos.push_back(Hello(Message,this));
}
void ExecuteAll()
{
for each(Hello h in Hellos)
h.Execute();
}
int NothingReally(int y)
{
int a = 0;
a += 1;
return a + y;
}
}
What I'm wondering is, is there any elegant solution for dealing with these issues? In say c#, and java, you're not restricted by this "linear" compiling.
Use header include guards, either "#ifndef / #define / #endif", or "#pragma once"
Put your code in a .cpp, not inline in the header
???
Profit
The reason this will work for you is because you can then use forward declarations of the class you want to reference without including the file if you so wish.
You are missing include guards
why define methods in the header?
Besides these problems with your code, to answer your question : normal way is to forward declare classes - not to include headers in headers (unless you have to).
If you follow a few basic rules, it is not awkward at all. But in comparison to e.g. Java or C#, you have to follow these rules by yourself, the compiler and/or language spec does not enforce it.
Other answers already noted that, but I will recap here so you have it in one place:
Use include guards. They make sure that your header (and thus your class definition) is only included once.
Normally, you will want to separate the declaration and implementation of your methods. This makes the header files more reusable and will reduce compilation time, because the header requires normally fewer #includes than the CPP (i.e. implementation) file.
In the header, use forward declarations instead of includes. This is possible only if you just use the name of the respective type, but don't need to know any "internals". The reason for this is that the forward declaration just tells the compiler that a certain name exists, but not what it contains.
This is a forward declaration of class Bar:
class Bar;
class Foo {
void foooh(Bar * b);
};
Here, the compiler will know that there is a Bar somewhere, but it does not know what members it has.
Use "using namespace xyz" only in CPP files, not in headers.
Allright, here comes your example code, modified to meet these rules. I only show the Hello class, the HelloPackage is to be separated into header and CPP file accordingly.
Hello.h (was Header1.h in your example)
#include <string>
class HelloPackage;
class Hello
{
public:
Hello();
Hello(std::string message, HelloPackage * pack);
void Execute();
private:
string Message;
HelloPackage * Package;
};
Hello.cpp
#include "Hello.h"
#include "HelloPackage.h"
using namespace std;
Hello::Hello() : Message("")
{}
Hello::Hello(string message, HelloPackage * pack)
{
Message = message;
Package = pack;
}
void Hello::Execute()
{
cout << Message << endl;
// Now accessing NothingReally works!
Package->NothingReally(8);
}
One question that may arise is why is the include for string is needed. Couldn't you just forward declare the string class, too?
The difference is that you use the string as embedded member, you don't use a pointer to string. This is ok, but it forces you to use #include, because the compiler must know how much space a string instance needs inside your Hello class.