Reputation: 18754
If I have a class definition
class myClass
{
void x();
};
void myClass::x()
{
hello(); // error: ‘hello’ was not declared in this scope
}
void hello()
{
cout << "Hello\n" << endl;
}
How can I call a function defined outside the scope of a class and located in the same file ? I know that I can use Namespace::function
but I am not sure in this case what I should use for Namespace
Upvotes: 0
Views: 2544
Reputation: 59637
Define the hello
function in the file ahead of where it's being used - before method x
- or supply a function prototype ahead of where it's being used:
void hello(); // function definition is later in the file
void myClass::x()
{
hello();
}
Upvotes: 4
Reputation: 258618
You must at least declare it (if not define it) before its use.
Usually, this is done in an anonymous namespace if the function's functionality is only used in that translation unit:
class myClass
{
void x();
};
namespace
{
void hello()
{
cout << "Hello\n" << endl;
}
}
void myClass::x()
{
hello(); // error: ‘hello’ was not declared in this scope
}
This gives the function internal linkage (similar to declaring it static
) and is only available in that TU.
Upvotes: 5