comma operator

B

bb

Hi,

Please could someone throw some light on why the following definitions
are not the same?

class A {

const int& a, b; // b does not get defined as a
ref. but a plain int

const int& x; const int& y; // obviously, both are refs.

...

};

Thanks.
 
V

Victor Bazarov

bb said:
Please could someone throw some light on why the following definitions
are not the same?

class A {

const int& a, b; // b does not get defined as a
ref. but a plain int

const int& x; const int& y; // obviously, both are refs.

...

};

It really has nothing to do with comma operator, you know.

The rules of declarations are such that '*' and '&' are part of the
individual object declaration, whereas the type (the 'const int' part
in your example) is common for all objects. IOW, the same thing would
happen if you declared 'a' as a pointer to const int:

const int* a, b; // 'a' is a pointer, 'b' is not.

To avoid mistakes like that, declare each object in its own separate
statement, or use typedefs:

typedef const int *pointerToConstInt;

pointerToConstInt a, b; // both 'a' and 'b' are pointers now

V
 
S

Supat Wongwirawat

It is the C++ syntax.
For reference and pointer you cannot declare like this

T& a,b,c;
T* a,b,c;

Only a will be reference/ pointer.
You have to specify * or & for every variable in the declaration.

const int &a, &b; will do what you want to accomplish.

Hope that helps.
 
T

Tomás Ó hÉilidhe

bb:
const int& a, b; // b does not get defined as a
ref. but a plain int

const int& x; const int& y; // obviously, both are refs.


In the "grammar" of C++, the ampersand and the asterisk are part of the
object's name rather than its type. That's why I write: int *p instead of
int* p.

Write a type, then write the names after it, separated by commas:

int *a, *b, *c, *d;

This grammar is what leads to declarations such as:

int (*p(double))[5];

Also don't confuse the comma within structs with the _actual_ comma
operator.
 

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

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top