Until now I've always used Getter/Setter in C++ like in Java to get a value from another class.
1 2 3 4 5 6
int number;
publicint getNumber()
{
return number;
}
But is there a better/faster way, like using a pointer?
because i think, when i retrieve the value via a getter it's just a copy, i'm right? So would it be faster(performance) if I would use pointer to get the value?
But is there a better/faster way, like using a pointer?
No.
because i think, when i retrieve the value via a getter it's just a copy, i'm right?
Yes, but that's the cheapest way to pass an int. It'll fit in a register and the langauge doesn't generate an extra memory access to deal with it. And that's if a function call was used, but it's probably inlined.
So would it be faster(performance) if I would use pointer to get the value?
No. The pointer would have to point somewhere in memory, and then we'd need to dereference it, ... A pointer is a variable, so we'd have to store that too... It's just a mess.
The point is, the code is likely to be inlined in C++, so it's equivalent to doing a variable assignment. It won't even generate a function call.
However, simple types do not benefit and in some cases the compiler can do return value optimization to elide copy. Summary: not always faster, nor better.
A good rule of thumb is to just do it simply, the way the language is designed to do it. The compiler will optimize its natural design to be very fast.
Don't worry about speed of things unless you notice that your program has speed issues. If you do, get out a profiler and use it to figure out where the speed problem or problems lie. Then fix those.