-3

Possible Duplicate:
Use of 'const' for function parameters

I am new to C++, came from java programming so the Reference weird uses in C++ comes unnaturally to me. I am not a new programmer, so I'd appreciate a serious deep and wide answer about this subject rather then just a shallow "when to use" only answer.

I want to know what are the differences between

const A& p; 

and

A& p;
Community
  • 1
  • 1
Ofek Ron
  • 8,354
  • 13
  • 55
  • 103
  • 2
    First is const, second is not. What is unnatural here? o.O – Griwes Jun 10 '12 at 13:07
  • 3
    @Griwes - what is unnatural is that Java and the .NET languages do __not__ have a clear concept of `const`-ness, which to (good) C++ programmers looks like a significant omission. – AAT Jun 10 '12 at 13:11
  • 1
    @AAT, wait, are we supposed to use Google for OP, or to be OP's "living encyclopedia"? Plus, we should ban teaching Java or .NET languages before C++... – Griwes Jun 10 '12 at 13:13
  • 2
    @bmarguiles how can this be a duplicate of a question that does not mention references and asks about function parameters only? – juanchopanza Jun 10 '12 at 13:16
  • @Griwes, I wasn't disagreeing with you, just making a slightly tongue-in-cheek point about Java and .NET. Maybe I should have put a ! – AAT Jun 12 '12 at 07:59

1 Answers1

3

const A& p is a reference to a constant object of type A.

A& p is a reference to a (non-const) object of type A.

jalf
  • 243,077
  • 51
  • 345
  • 550
  • `const A& p` is a const reference to an object of type `A` which may or may not be `const` itself. – Ferruccio Jun 10 '12 at 14:00
  • 2
    @Ferruccio: No. there is no such thing as a "const reference" in C++. What would it mean? A reference is *never* mutable, in the sense that you can never set it to point to a different object. You have references to const objects and references to non-const objects. But you don't have const references – jalf Jun 10 '12 at 14:58
  • 1
    Could it be less informative? you didnt help me at all.. – Ofek Ron Jun 10 '12 at 16:44
  • @OfekRon: then perhaps you should be clearer about what you want to know. And perhaps you should drop the attitude, because I was actually trying to answer your question (unlike all the others who voted to close it). What exactly is it you don't understand? Do you know what a const object is? Do you know what a reference is? – jalf Jun 10 '12 at 17:13
  • 1
    @jalf - Yes, of course the reference itself is never mutable. That was a poor choice of terms on my part. What I meant is that if you write `const A& p = q;`, even though `q` may be mutable, you can't change it through `p` without invoking undefined behavior. – Ferruccio Jun 10 '12 at 19:49