-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;
5
  • 2
    First is const, second is not. What is unnatural here? o.O Commented Jun 10, 2012 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. Commented Jun 10, 2012 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++... Commented Jun 10, 2012 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? Commented Jun 10, 2012 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 <g>! Commented Jun 12, 2012 at 7:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

const A& p is a const reference to an object of type A which may or may not be const itself.
@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
Could it be less informative? you didnt help me at all..
@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 - 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.