d33tah
d33tah

Reputation: 11561

Should I enforce a C++ interface at runtime or compile time?

I found this in Nmap's source code:

/** This function MUST be overwritten on ANY class that inherits from          
  *  this one. Otherwise getBinaryBuffer will fail */                          
virtual u8 * getBufferPointer(){                                               
    netutil_fatal("getBufferPointer(): Attempting to use superclass PacketElement method.\n");
    return NULL;                                                               
 } /* End of getBufferPointer() */                                             

If getBufferPointer were pure virtual, any derived classes failing to implement it would be caught at compile time. Why would it be better to opt for a runtime error as opposed to one triggered by the compiler?

Upvotes: 0

Views: 249

Answers (2)

Raven
Raven

Reputation: 1520

One should never prefer a run time error over a compile time error, especially when the language provides an easier way to do exactly what you want which will also give a compiler error. In my 5+ years of C++ coding I have never encountered a reason to use your way to create methods.

Run time error = Many possible causes, and I need my own debugging statements to find it. Possibly need to run the program many times as well. In your case I may have other classes which fail to override the method, which may cause errors at some undefined point.

Compile time error = One cause, and my compiler tells me what's up.

Upvotes: 2

cpp_learner
cpp_learner

Reputation: 382

Just make it pure virtual i.e.

 virtual u8 * getBufferPointer() = 0;

so that any subclass derived from its parent class(PacketElement) should redefine it.

Upvotes: 1

Related Questions