Sep 22, 2016 at 1:07am UTC
I have a function that returns a struct. If and else statement. How do I write it with one return without unnecessary stuff since I can't return a null object?
Sep 22, 2016 at 2:07am UTC
Can you show your current code?
Sep 22, 2016 at 2:18am UTC
Are you making a struct to return or are you simply trying to return a reference to an object.
Sep 22, 2016 at 2:54am UTC
I am returning a pointer 'this', but isn't that an object?
Last edited on Sep 22, 2016 at 2:54am UTC
Sep 22, 2016 at 3:04am UTC
Well here are some partial pseudo code possibilities, there is probably more ways doing of this but here are some.
The this pointer points to the internals of a class or struct, which are objects.
Return nullptr or this. Check if it's not nullptr after calling to ensure safety.
1 2 3 4 5 6 7 8
type* getStruct() {
if (condition) {
return this ;
}
else {
return nullptr ;
}
}
Using an exception and then when you call it you check for exception.
1 2 3 4 5 6 7 8
type& getStruct() {
if (condition) {
return *this ;
}
else {
throw std::logic_error("invalid condition" );
}
}
Pass in an object and assign to this otherwise assign nullpltr. Then you could check after the pointer you passed in after calling.
1 2 3 4 5 6 7 8
void getStruct(type* obj) {
if (condition) {
obj = this ;
}
else {
obj = nullptr ;
}
}
I'd probably choose the first one but there could be a better way.
Last edited on Sep 22, 2016 at 3:05am UTC
Sep 22, 2016 at 10:58am UTC
What if it is *this instead of this?