Reputation: 947
So I'm working with this code that looks like this:
class SomeClass : public SomeBaseClass {
SomePointerToClass * p;
public:
SomeClass(SomePointerToClass* p = NULL) : p(p) {};
void start(SomePointerToClass* sp) {
p = sp;
}
bool hasStarted() {
return p;
}
}
I simplified some stuff so that I could make a short code example, but I think the returning a bool from a member variable pointer is a bit of a codesmell. Should I change it or is this some form of C++ convention?
Upvotes: 1
Views: 152
Reputation: 2787
bool hasStarted () { return (bool) p; }
This makes it clear "I meant to do that," and is, I'd say, a very reasonable thing to do.
I sometimes do this inside a function that has access to a pointer p:
if (p) ... //meaning: if p isn't NULL...
but the consensus is I shouldn't mention returning a pointer -- and I'm sure the consensus is correct here. So edited.
Upvotes: 0
Reputation: 385174
hasStarted()
is fine: in C++, the pointer will be automatically converted to bool
on a zero/not-zero basis.†
Some people prefer to write return (p != nullptr)
or return static_cast<bool>(p)
instead, in order to be really explicit about intent, but I'm not terribly fussy about that in cases like this.
† However, the behaviour is implementation-defined in C, so do not rely on it there!
Upvotes: 3