[A89] Re: C question
[Prev][Next][Index][Thread]
[A89] Re: C question
> I was wondering, when declaring a function, say a copy constructor for a
> class, why should you use const to pass the value? something like
> "someClass::someClass(const someClass &a)" or something along those lines.
> what is the advantage or point even of using const instead of not using
it?
const has several advantages, and I'd highly recommend using it whenever
possible.
First of all, the obvious answer -- it keeps you from doing something stupid
and reassigning a constant with a new value.
Second, and much more importantly, the compiler can make some _huge_
optimizations when it knows a variable is a constant. If a value is
constant, it can be inlined by the compiler, thus preventing it from
allocating memory and performing slower operations to read and write from
that memory. In the example you put above, it's especially useful - there's
typically a major difference in the way that the compiler treats const and
non-const reference parameters.
Third, if you're writing a class, all accessors should be constant funtions.
If so, they can be called even with const instances of the class; if not,
then you won't be able to call them.
If you have a const variable that you try to send into a function that isn't
expecting a constant, then the compiler should give you a problem. This is
more often a problem when you're using functions written by someone else
(case in point: TI's SDK. Many functions that take string inputs don't
modify them, such as WinStrXY, but TI did not define those inputs as const.
The result is a compiler warning every time you try to call the function
with a constant variable, unless you cast away its constness, which should
be unnecessary).
And the last one I can come up with off the top of my head is when you're
writing functions that someone else uses, in which case they might run into
the problem I referred to in the above paragraph. In general, if a value is
constant, mark it const and let the compiler handle it. It certainly never
hurts, and it's almost always helpful -- often time s you may not notice it
if you don't make the obvious error of trying to write to a const variable,
but it can create huge differences in performance under the hood.
I'm sure there are other advantages I forgot to list here. A really good
explanation in some of these can be found in the book _Effective C++_ by
Scott Meyers, although I would only recommend that for fairly experienced
programmers (and it's a great book for them).
-Scott