0
class ABC{
     public :
      int a;
     public :
      int getData(){
        return a;
      }
     }
     void main()
     { 
       ABC abc;
       cout<< abc.a;    //1
       cout<<abc.getData();//2
     }

Now if I'm accessing the variable "a" in which case compiler take less time to access 'a'. I guess first case but not sure.

sank
  • 5
  • 4

3 Answers3

1

The two methods are not strictly equivalent:

  1. Directly accessing the member reads the value of the member itself while
  2. The get method returns a copy of the variable, so you read from the copy as such.

With regards to performance ofcourse #1 should be faster since no copy is involved, but most modern compilers will apply copy elision to remove the extra copy being created.

Rather that performance you should consider uniformity of the coding guidelines followed in your organization/institute.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • I don't think copy elision can apply here, but the "as-if" rule would allow no copy to be made under the right circumstances. – juanchopanza Jul 24 '13 at 06:06
1

It is all coding style. Having private members is only a security measure so that any external entity doesn't have access to it directly and modifies it (kind of the same concept of declaring a variable const which is used as a security barrier). Public accessors are functions used to access the member values and public modifiers are used to change the value through a function. It is simply coding convention. It would be faster to pass a member directly rather than a function since no copies are made.

theta
  • 179
  • 11
0

I would put it like this:

  • If there is anything in the accessors other than simply setting/returning the variable (like a range check, for example), the variable should absolutely be private. This is the only way to ensure that this additional code actually gets executed.

  • If you only need one accessor because you either do not want the variable to be inquireable or setable, the variable should be private as well.

  • If you would define both a vanilla getter and setter, I think, it's just as safe to make the variable public and forget about the accessors. The variable is defacto public anyway. The accessors would just be redundant code in this case and therefore should not bloat your code. And it is easy to make a public variable private later on, because the compiler will dutifully list each and every line of code you need to adapt.

In short: use private variables by default, and think twice about every accessor you write since it will punch a hole into your encapsulation.

cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106