access to member array via public members

R

Richard Herring

In message said:
Richard said:
Rolf Magnus said:
Richard Herring wrote:

Just do this:

cat foo.cc
class foo {
private:
// representation
float a[3];
public:
// functions
const
float& x(void) const { return a[0]; }


Const function returning non-const reference to member? Are you sure?


Where?
Right there:
float& x(void) const { return a[0]; }
A constant function taking no arguments and returning a non-const
reference to a float, namely a[0].

I guess you're not so good at reading declarations that span two lines,
are you?

Only when I write them ;-)

It's been a long day. I take that point back, and substitute a
different one. Who on earth splits that kind of declaration over two
lines, unless they deliberately intend to cause confusion?
Just look at the line _preceding_ the one you're referring to.

But my comment about the following line still stands.
 
B

Billy

I was infact using "getters" with my initial implementation. I came to
the same realization as Richard; that by using getters I might as well
just make them public.

The implementations are about equal length because I needed to add a
copy cons. and assign. op. for the implementation using reference
members.

I am fairly convinced that using assignment and getters can be only "as
good" as using memcpy and public access. Though as Rolf has pointed
out, the only way to surely tell is to profile and/or look at the
assembly.

Thanks everyone for your help and opinions. -J

"And yet, if the OP doesn't know how to initialize the array, I doubt
fully they understand the the need for the 'efficiency'" -Andrew

I am pretty sure I understand the need for efficiency. I am just not a
seasoned c++ programmer. That's why I am asking for help.
 

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,294
Messages
2,571,511
Members
48,206
Latest member
EpifaniaMc

Latest Threads

Top