Question

I understand that return values with co-variant types can differ in case of virtual functions. I wish to know if there is a possible way through which I can have an empty declaration in my base class's virtual function without returning NULL and still not having this:

Error: no return statement in function returning non-void

I do not wish to use pure virtual functions as it will clutter all derived classes with empty declarations of the virtual function.

Is there any other approach to this problem?

Was it helpful?

Solution

if their is a possible way through which i can have an empty declaration in my base class's virtual function without returning NULL and still not having [error]

Certainly not. If you have a function that's declared to return a value, why would you expect to be able to define it not to? If the function's pure virtual, then you don't "clutter all derived classes with empty declarations of the virtual function", you leave it pure virtual until you have a meaningful value to return (or use NULL). It makes no sense to talk of having an non-abstract class where the function doesn't work as implied by the declaration: if that's the way your classes are shaping up, you should consider removing the function from the API, reconsidering why you're opposed to NULL, or throwing an exception instead.

OTHER TIPS

So your base class function must return some value, and the type must be co-variant with the return type(s) you will use in your derived class (which naturally brings to mind base-class-pointers and derived-class-pointers).

Your requirement is that you want to avoid passing a NULL pointer. One possibility would be to create a particular null object (some kind of object representing a lack of any meaningful result, as opposed to an actual NULL pointer)

I suppose you could return a null object for the base type return type.

According to the C++ STandard

2 A return statement with neither an expression nor a braced-init-list can be used only in functions that do not return a value, that is, a function with the return type cv void,

And

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

I do not see the reason why the virtual function in your base class can not be declared as a pure virtual function if you have no its realization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top