[SDL] Const correctness for SDL video

Martin Storsjö martin at martin.st
Wed Feb 14 13:41:14 PST 2007


On Wed, 14 Feb 2007, Bob Pendleton wrote:

> Just curious, why do you care enough about this to bother with doing all
> this work? I teach C++ and I really don't see the point? Could you
> educate me on this subject?

Some C++ frameworks use the const keyword very much, and in such cases the 
code interfacing with C-libraries (e.g. SDL) will need lots of ugly casts 
unless the libraries actually have parameters marked const where needed.

Const in C++, correctly used, can really give nice strictness of the code, 
which easily points out bad design decisions. And complicates things when 
one wants to do quick hacks, of course. ;-) As to how much it actually 
reduces the amount of bugs, I've got no clue...

Const in C++ can e.g. be used on class methods, e.g.:

int MyClass::getValue() const {
     return value;
}

const MyClass* someObject;
int value = someObject->getValue();
someObject->setValue(42); // probably disallowed unless setValue also
                           // would be marked const...

The only methods which can be called on a const object (or object pointer) 
are the methods marked const. And within these methods, all member 
variables are regarded const, so you can only call the const methods of 
the member objects, etc. Using this is usually quite an 
all-or-nothing-effort, when wanting to mark a method const, one usually 
have to fix the same for all methods called within that method, 
recursively.

And in some cases, e.g. when overriding methods from some base class from 
some other library, one can't even decide oneself whether to enforce this 
design in the application. Another example where this is required is when 
defining operators for classes. The operands to e.g. the + operator have 
to be const, naturally.

Of course, I won't try to say anything about whether adding casts to the 
code interfacing to e.g. SDL or actually cleaning up the const-ness of SDL 
is easier...

// Martin


More information about the SDL mailing list