473,394 Members | 1,699 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

The "const" modifier

What exactly is the sense of using a "const" modifier before a function
declaration? Actually, you can use it in three places. For instance, take a
look at the following function declaration (from the introductory book
"Absolute C++" by W. Savitch, p. 315)

class Money
{
Money();
const Money operator + (const Money& amount2) const;
private:
int dollars;
int cents;
}

I didn't copy the whole code (there are many more member functions), but
this should suffice for the question.

The meaning of the "const" before the parameter "amount2" is obvious to me;
the "const" just before the semicolon signals that the function may not
change the calling object if I got it right. But what about the first
"const"?

Cheers,
Matthias

--
Für emails Anweisung in der Adresse befolgen
Jul 22 '05 #1
11 4731
Der Andere wrote:
What exactly is the sense of using a "const" modifier before a function
declaration? Actually, you can use it in three places. For instance, take a
look at the following function declaration (from the introductory book
"Absolute C++" by W. Savitch, p. 315)

class Money
{
Money();
const Money operator + (const Money& amount2) const;
private:
int dollars;
int cents;
}

I didn't copy the whole code (there are many more member functions), but
this should suffice for the question.

The meaning of the "const" before the parameter "amount2" is obvious to me;
the "const" just before the semicolon signals that the function may not
change the calling object if I got it right. But what about the first
"const"?

Cheers,
Matthias

--
Für emails Anweisung in der Adresse befolgen


These issues are discussed in the C++ FAQ:
http://www.parashift.com/c++-faq-lit....html#faq-29.6
http://www.parashift.com/c++-faq-lit...rrectness.html

Searching the FAQ before posting is always an excellent idea.
One should also search the newsgroups too.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Jul 22 '05 #2
Der Andere wrote:
What exactly is the sense of using a "const" modifier before a function
declaration? Actually, you can use it in three places. For instance, take a
look at the following function declaration (from the introductory book
"Absolute C++" by W. Savitch, p. 315)

class Money
{
Money();
const Money operator + (const Money& amount2) const;
private:
int dollars;
int cents;
}

I didn't copy the whole code (there are many more member functions), but
this should suffice for the question.

The meaning of the "const" before the parameter "amount2" is obvious to me;
the "const" just before the semicolon signals that the function may not
change the calling object if I got it right. But what about the first
"const"?


It means the returned temporary object is const. I posted a thread about
this a while back:

http://groups.google.com/groups?thre...733r%404ax.com

Unfortunately it didn't generate much discussion. That thread was
prompted by GotW #6, here:

http://www.gotw.ca/gotw/006.htm

Which may be enlightening for you.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #3
Thomas Matthews <Th*************************@sbcglobal.net> wrote:
Der Andere wrote:
What exactly is the sense of using a "const" modifier before a function
declaration? Actually, you can use it in three places. For instance, take a
look at the following function declaration (from the introductory book
"Absolute C++" by W. Savitch, p. 315)

class Money
{
Money();
const Money operator + (const Money& amount2) const;
private:
int dollars;
int cents;
}

I didn't copy the whole code (there are many more member functions), but
this should suffice for the question.

The meaning of the "const" before the parameter "amount2" is obvious to me;
the "const" just before the semicolon signals that the function may not
change the calling object if I got it right. But what about the first
"const"?


These issues are discussed in the C++ FAQ:
http://www.parashift.com/c++-faq-lit....html#faq-29.6
http://www.parashift.com/c++-faq-lit...rrectness.html

Searching the FAQ before posting is always an excellent idea.
One should also search the newsgroups too.


I don't see where his question is answered in the FAQ...
Jul 22 '05 #4
Der Andere wrote:
What exactly is the sense of using a "const" modifier
before a function declaration? Actually, you can use
it in three places. For instance, take a look at the
following function declaration (from the introductory
book "Absolute C++" by W. Savitch, p. 315)

class Money
{
Money();
const Money operator + (const Money& amount2) const;
private:
int dollars;
int cents;
}

I didn't copy the whole code (there are many more member
functions), but this should suffice for the question.

The meaning of the "const" before the parameter "amount2"
is obvious to me; the "const" just before the semicolon
signals that the function may not change the calling
object if I got it right. But what about the first
"const"?


It means the Money temporary returned by operator+ is
const. If that const was not there, the compiler would
merrily accept this (if op+= was defined, of course):

Money a, b, c, d;
a = (b + c) += d;

With the const, the compiler would complain. The argument
made for returning const objects is to prevent cases like
that above, because you can't write (b+c)+=d for built-in
types. The idea is that making classes behave more like
build-in types is better. I don't much see the point. If
the user wants to write (b+c)+=d, I say let 'em, even if it
wouldn't work with int or double.
Jul 22 '05 #5

"Derek" <no**@cheese.com> wrote in message
news:c6************@ID-46268.news.uni-berlin.de...
... The idea is that making classes behave more like
build-in types is better. I don't much see the point. If
the user wants to write (b+c)+=d, I say let 'em, even if it
wouldn't work with int or double.


And I say, if they *do* write code like that...shoot 'em! :-)

Honestly, I think the fact that C++ allows so many varied and complex ways
of combining operations into one line of code has caused more maintenance
headaches than they're worth. I love C++, but I almost always put one and
only one operation on a line of code, and let the optimizer reduce it if
wants to. I want my code to readable (and debuggable). Better three lines
of readable code than one line that requires three hours of research to
decipher. Maybe it's just the old Pascal programmer in me, but that's my
opinion anyway.

(Of course, if it's job security you're after, maybe writing indecipherable
code is a *good* thing...?)

-Howard

Jul 22 '05 #6
> > class Money
> {
> Money();
> const Money operator + (const Money& amount2) const;
> private:
> int dollars;
> int cents;
> }
> The meaning of the "const" before the parameter "amount2"
> is obvious to me; the "const" just before the semicolon
> signals that the function may not change the calling
> object if I got it right. But what about the first
> "const"?


It means the Money temporary returned by operator+ is
const. If that const was not there, the compiler would
merrily accept this (if op+= was defined, of course):

Money a, b, c, d;
a = (b + c) += d;

With the const, the compiler would complain. The argument
made for returning const objects is to prevent cases like
that above, because you can't write (b+c)+=d for built-in
types. The idea is that making classes behave more like
build-in types is better. I don't much see the point. If
the user wants to write (b+c)+=d, I say let 'em, even if it
wouldn't work with int or double.


Got the point :-)
If I'd use const everywhere I _should_ do, the code would probably get
awkward beyond recognition. I won't use the first const anyway ... I trust
in myself to not produce such a degree of non-sensical code, so I agree with
you.

Regards,
Matthias
Jul 22 '05 #7
"Der Andere" <ma**************@gmx.net> wrote in message news:<c6*************@news.t-online.com>...

*snip*
If I'd use const everywhere I _should_ do, the code would probably get
awkward beyond recognition.
*Sigh* You wouldn't feel this way if you'd taken the time to read (and
think about and try to understand)
1) the FAQ links
(http://www.parashift.com/c++-faq-lit....html#faq-29.6
http://www.parashift.com/c++-faq-lit...rectness.html), or

2) the Guru-of-the-week entry (http://www.gotw.ca/gotw/006.htm),

as suggested by other posters in this thread. Proper use of const is
absolutely essential for proper, readable, debuggable C++ code. In
particular, the distinction between returning a const & or non-const &
can be extremely important for designing certain types of classes
(c.f. Stroustrup's TC++PL section 5.5).
I won't use the first const anyway ... I trust in myself to not produce such > a degree of non-sensical code


Wow! You have demonstrated don't even understand proper use or even
the potential benefits of the const qualifier yet .. which makes your
statement above highly dubious. Perhaps you would really would never
construct such and artificially awkward mathematical expression, but
there are myriad other ways to generate "non-sensical code". If you
are serious about programming in C++, you should really reconsider
your (by inference) cavalier attitude towards essential language
features like the const qualifier.
Jul 22 '05 #8
Der Andere wrote:
Got the point :-) If I'd use const everywhere I
_should_ do, the code would probably get awkward beyond
recognition. I won't use the first const anyway ...
I trust in myself to not produce such a degree of
non-sensical code, so I agree with you.


Const correctness is important. MOST of the time I use
const wherever I can. There are very few cases where I
don't use const when I can. You example just happens
to be one of the cases where I choose not to:

const AnotherClass operator+(...); // I wouldn't use
// const here

There are other examples, but not many. SOMETIMES it's
better to use iterator instead of const_iterator (see
"Effective STL" by Scott Meyers), and I don't usually
bother to const local variables:

int x = (a + b) / c * d; // could declare x const,
// but I usually don't

But in all of the other common cases I use const very
rigorously (e.g., passing arguments by reference to
const, member functions, constants, etc.)

What I'm trying to stress is that const is a Good Thing
and you should use it wherever possible (and practical).
There are cases where const can be disregarded, but
think of them as exceptions to the rule.
Jul 22 '05 #9
* Daniel T. <po********@eathlink.net>:
Thomas Matthews <Th*************************@sbcglobal.net> wrote:
Der Andere wrote:
class Money
{
Money();
const Money operator + (const Money& amount2) const;
private:
int dollars;
int cents;
[...]
The meaning of the "const" before the parameter "amount2" is obvious to me;
the "const" just before the semicolon signals that the function may not
change the calling object if I got it right. But what about the first
"const"?


These issues are discussed in the C++ FAQ:
http://www.parashift.com/c++-faq-lit....html#faq-29.6
http://www.parashift.com/c++-faq-lit...rrectness.html

Searching the FAQ before posting is always an excellent idea.
One should also search the newsgroups too.


I don't see where his question is answered in the FAQ...


You're right. I also didn't find it.
But as this postin ointed me to some usefull knowledge about const it
wasn't totally pointless.

David

--
,' David Riebenbauer - Student at Technichal University of Graz ~~~|
/' / da*****@sbox.tugraz.at /_,~""~""/ ICQ: 322056002 -\/- Playlist: |
< /' Fernbedienung ~= Macht ,/'*','* '/ Die geht euch nichts an! |
/\/\/\/\/\/\/\/\/\/\/\/\/\/' /)/(\ |/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
Jul 22 '05 #10
"Der Andere" <ma**************@gmx.net> wrote in message
news:c6*************@news.t-online.com...
Got the point :-)
If I'd use const everywhere I _should_ do, the code would probably get
awkward beyond recognition. I won't use the first const anyway ... I trust
in myself to not produce such a degree of non-sensical code, so I agree with you.


const allows the compiler to optimize code in ways that may not be obvious,
and it can prevent bugs by refusing to compile code that appears correct but
is either incorrect or just nonsensical.

S

Jul 22 '05 #11
Stephen Sprunk wrote:
"Der Andere" <ma**************@gmx.net> wrote in message
news:c6*************@news.t-online.com...
Got the point :-)
If I'd use const everywhere I _should_ do, the code would probably
get awkward beyond recognition. I won't use the first const anyway
... I trust in myself to not produce such a degree of non-sensical
code, so I agree with you.
const allows the compiler to optimize code in ways that may not be
obvious,


It is questionable if it really helps optimization
(http://www.gotw.ca/gotw/081.htm). But...
and it can prevent bugs by refusing to compile code that
appears correct but is either incorrect or just nonsensical.


....is as far as I am concerned the most important reason for using const.
Documenting your intentions to whoever has to use and/or maintain the code
(which may very well be you in few months) being a close second.

--
Peter van Merkerk
peter.van.merkerk(at)dse.nl
Jul 22 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: bucher | last post by:
Hi, I want to push a const auto_ptr into a vector, but the compile reports errors. Below is the code. class Folder; class Result; class Results { public: int size(){return _Items.size();}
3
by: H. S. | last post by:
Hi, I am trying to compile these set of C++ files and trying out class inheritence and function pointers. Can anybody shed some light why my compiler is not compiling them and where I am going...
3
by: Alexander Farber | last post by:
Hi, does anyone have an idea, why do I get the following error (I have to use g++296 on RedHat Linux as compiler): In file included from r_dir.cpp:9: r_obey.h:262: declaration of `const...
3
by: Markus.Elfring | last post by:
How much effort do you invest to develop a const-correct design? Did a later addition of the type modifier "const" for a function interface uncover any real errors and bugs in your source code at...
9
by: July | last post by:
Hello! consider the following code: class A { public: virtual void f() const{ cout << "A::f()" << endl; } };
4
by: C. J. Clegg | last post by:
A month or so ago I read a discussion about putting const ints in header files, and how one shouldn't put things in header files that allocate memory, etc. because they will generate multiple...
9
by: Gary | last post by:
Hi all! I've taken some time on learning the difference between "pointers to const variables" and "const pointer variables". The question is: in the following code, can we change the contents of...
20
by: liujiaping | last post by:
I'm confused about the program below: int main(int argc, char* argv) { char str1 = "abc"; char str2 = "abc"; const char str3 = "abc"; const char str4 = "abc"; const char* str5 = "abc";
8
by: not_a_commie | last post by:
A method parameter declared as "const ref" would allow for passing large structs quickly and enforce that the struct does not get reassigned. I know there was concern before about the inability of...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.