Reputation: 4995
A problem I'm working on is asking me to define an istream constructor inside the class body. Let's call the class Sound. Now this constructor uses a function in its own body. But the function is supposed to be a non-member function. I have it defined in another file, but I have it declared in the header that contains the class definition itself. I've placed the header in the other file containing the non-member functions already.
The problem is, one of the parameters of the non member function has type Sound and it performs operations on the type Sound objects.
When I declare this function in the header file, if I put it before the class definition I get an error saying the objects haven't been defined.
When I put the declaration after the definition, the constructor now tells me that the function inside it's body is undefined.
If I put the declaration inside the class body, it becomes a member function.
The problem didn't explicitly state that I cannot make the function a member function so I am wondering if there is a way to overcome this catch-22.
Upvotes: 2
Views: 577
Reputation: 1669
Looks like best thing to do is to use forward declaration for class, before the function:
header:
class Sound;
void f(Sound s);
class Sound
{...};
Upvotes: 1
Reputation: 1399
Upvotes: 0
Reputation: 53225
You do not necessarily need to make the function member. You can have at least two ways to solve it in a different manner.
The problem is that you are having all this in a situation where a Sound object is not yet defined if I understand correctly.
1) You can refactor your code a bit as demonstrated below.
header
file:
class Sound
{
public:
Sound();
doStuff();
}
cpp
file:
void non_member_function(Sound sound)
Sound::Sound() { non_member_function(*this); }
Sound::doStuff() {}
void non_member_function(Sound sound) { sound.doStuff(); }
2) if you insist on the scenario aforementioned, you put a Sound sound
forward declaration before the non-member function to get the type recognized. Or, you can just put the declaration after the class declaration.
header
file:
class Sound
{
public:
Sound();
doStuff();
}
void non_member_function(Sound sound)
cpp
file:
Sound::Sound() { non_member_function(*this); }
Sound::doStuff() {}
void non_member_function(Sound sound) { sound.doStuff(); }
Upvotes: 2