Re: cannot convert 'this' pointer from 'const class MyClass'
From: josh (smileyfaceswillruletheworld_at_yahoo.com.NOSPAM)
Date: Tue, 07 Sep 2004 12:34:49 -0700
Joshua Weir wrote:
> Thankyou, you were right i made the parent function not const and it worked
> fine. THis leaves me with 1 last question. When and why do you make a
> function const. it seems to be more of a hassle than its worth!
If I were to give you a simple rule of thumb, it would be wrong, but it
would be: use const whenever you can. Leave it off when you must. It's
not always easy to decide which a given case falls into, esp. with
Why? OOP is all about restricting what you can do and where.
In very small programs, it's easier to write the code when you can do
anything anywhere. If you need a variable changed, just go in and
change it. When programs get larger, that doesn't work so well. It
becomes impossible to keep track of everything. So you start limiting
what can be done where.
If you wrap stuff into a class, you know that nothing outside will be
messing with your private data. If something goes wrong in there, you
now have a much smaller amount of code to look through. At the same
time, a lot less code is directly accessing it, so you're less likely to
screw something up. If anything else tried to get at it, the compiler
would whine and complain at you.
const is another way to restrict things. If half of your member
functions are const, you can now rule out half of the code you'd
otherwise have to check. It also can force a cleaner design; if render
really shouldn't modify the object, it should be const, and you're now
forced to find another place to do your modifications.
But it's not always easy to decide exactly what should be possible in
what places. IMO this is just one of those things you learn with
experience. If you're just starting off, you can mostly survive without
const while you get a grasp on the rest of the language. Eventually
it'll make sense.
The basic principle is that you want to restrict what a given section of
code can do down to exactly what it's meant to do, and restrict the
amount of code that can do something down to only that which actually
needs to do it. Then you know that nothing can possibly go wrong.
Unfortunately, taken to extreme this will overwhelm the actual algorithm
with structure, but usually there's a happy moderation that can be achieved.