I have an application involving objects of different class types. The objects are referenced by pointers. A null pointer signifies that the associated object does not exist. Currently the calling codes is cumbersome, because each time it uses a pointer to an object, it tests the pointer value for null, and take some appropriate action it is null. Because the default action to be taken in the case of non-existence depends on the type of object, I would prefer to encode it in the classes for the objects themselves rather than in the calling program. This results in constructions like the following:
class C
{ ...
void member_func() //non-virtual !
{ if (this) { do something with the object ... }
else { take some default action }
}
...
};
Clearly the member function cannot be virtual, because the lookup table does not exist when the object does not exist, and the virtual call would fail. But is this code legal C++ for non-virtual member functions? It seems to work correctly for the compilers I have tried it on, but I am worried about possible non-portability. In the standard I can’t find a clause that either expressly allows or expressly prohibits such constructions.
this
will never be null in a member function so the check you perform is useless.
As pointed by Matthieu M. in a comment, if you do something like this in your code:
C* c = 0;
c->member();
This would cause undefined behavior and that is something bad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With