why const member, reference member can only be initialized not assigned

W

ww

I read a couple of books that tells this, but seems not one can
explain why is this


thanks
 
V

Victor Bazarov

ww said:
I read a couple of books that tells this, but seems not one can
explain why is this

A const member is constant. Assignment requires a modifiable
object. So, assignment is not an option for 'const', they need
to be initialised. References can be "assigned to", although they
execute the assignment so that the referred object is assigned to.
However, in order to refer to anything, they have to be initialised
and that's the only way to make a reference to refer to something.
That's why const members and members that are references need to be
initialised.

V
 
C

cplusplus

Hey loser why don't you do something productive with your life rather
than sulk like a dog
 
J

Jonathan Lane

I read a couple of books that tells this, but seems not one can
explain why is this

thanks

For references, the standard says that you cannot reseat them. I guess
that the technical reason is that when you call operator= it modifies
the value in the reference not the reference itself - which is what
you would expect.

int a = 3;
int& b(a);
//this will change the value of b not what it refers to
b = 5;

Since we can't reseat a reference it has to be defined at creation
time and hence assigned.

Likewise for const members, we can't call the assignment operator on
it so it must be initialised not assigned into. The const keyword
tells the compiler that calling the assignment operator is a syntax
error but we must have a mechanism to initialise which is done in the
constructor.
 
J

James Kanze

For references, the standard says that you cannot reseat them. I guess
that the technical reason is that when you call operator= it modifies
the value in the reference not the reference itself - which is what
you would expect.

The technical reason is that it is illegal to create a reference
or a const object with a trivial constructor without
initializing it. Regardless of whether they are members or not.
If they are members, of course, the only way you can initialize
them is in the initialization list; once you get into the body
of the constructor, they've been initialized.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top