Quick question regarding member access

M

mailforpr

Hello.

Given is the following class:

class Test
{
public:
int i;
int& get() { return i; }
};

Now, is the following member access

Test test;
test.i; // this here

equivalent to this method call?:

Test test;
test.get();

Do I have to worry about what is faster? If they are not equal, do
compiler optimize to get rid of this difference in accessing the
member(s)?

Thanks in advance.
 
R

ravinderthakur

no both of them are different. Its compiler's job to decide if it wants
to optimize this or not and it has all the reasons to do this. U can
try suggesting teh compiler by saying making it inline but that's all u
can do...


in nutshell test.get() will can never be faster than test.i.


thanks
ravinder thakur
 
M

mailforpr

Thanks.

It is very important for me to know that, because I am about to write
an application that will execute either test.i or test.get() about a
million times. So I am not sure which to use.
 
R

ravinderthakur

although that might be important for you, making the member variables
public or returning them by reference is never an accepted way of
writing the OO code.
 
K

Kai-Uwe Bux

although that might be important for you, making the member variables
public or returning them by reference is never an accepted way of
writing the OO code.

a) Well, then the code is not OO but fast. That doesn't need to be a bad
thing :)

Seriously: whether public member variables are cool or uncool depends very
much on the context. For instance, even in OO design there are cases where
the following is perfectly fine:

class OO_Thing {
private:

struct Internal_Data {

// lots of public members

}; // Internal_Data

public:

// some stuff not exposing Internal_Data at all

}; // OO_Thing


b) Please do not top-post. It is considered poor form in this news group.


Best

Kai-Uwe Bux
 
B

Bo Persson

Thanks.

It is very important for me to know that, because I am about to
write
an application that will execute either test.i or test.get() about a
million times. So I am not sure which to use.

You should use the one that makes your code easier to understand.

If you have a compiler that cannot optimize your get() function, you
are in a lot of trouble elsewhere!

Also, on a 3 GHz machine, one million accesses take no time flat -
whatever you do. You have *billions* of instructions per second to
play with!



Bo Persson
 

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,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top