Reputation: 51
I've the following source code for my ostream
ostream& operator << (ostream& os, AnimalsDirectory& a) {
for(int i=0;i<a.directorySize;i++) {
return os << a.animals[i];
}
}
When I compile this code it produces me the following error:
ContactDir.cpp:64:1: warning: control may reach end of non-void
function
[-Wreturn-type]
}
^
I don't know why this error occurs, I do it on objects animals array and want '<<' print all info about what this array has. Thanks in advance!
Upvotes: 0
Views: 214
Reputation: 469
Have a look how the operator method you want to implement is declared. You have to return a reference to a ostream object which is the one you get in your first parameter.
Secondly you have a return statement in your loop which will quit the function in the first loop cycle. What you probably want to do is something like this
ostream& operator << (ostream& os, AnimalsDirectory& a) {
for(int i=0;i<a.directorySize;i++) {
os << a.animals[i];
}
return os;
}
This requires that each animal object has also the <<-operator implemented
Upvotes: 2
Reputation: 36483
for(int i=0;i<a.directorySize;i++) {
return os << a.animals[i];
}
Let's see.. what if a.directorySize == 0
?, then i < a.directorySize
is false for i = 0
which means the loop never runs, which means the return
statement will not be reached. This invokes undefined behavior as there is nothing to return after the loop. For this the compiler issues a warning.
Furthermore, your code looks odd to say the least, you usually never loop only to unconditionally return.
Upvotes: 0