This is a rather old topic: Are setters and getters good or evil?
My question here is: do compilers in C++ / D / Java inline the getters and setter?
To which
Any JVM (or compiler) worth its salt needs to support inlining. In C++, the compiler inlines the getters and setters. In Java, the JVM inlines them at runtime after they have been called "enough" times. I don't know about D.
A getter would be required for certain members in some cases. However providing a getter and setter for each data member of a class is not a good practice. Doing that would be complicating the class's interface. Also setters would bring in resource ownership issues if not handled properly.
In D, all methods of classes, but not structs, are virtual by default. You can make a method non-virtual by making either the method or the whole class final. Also, D has property syntax that allows you to make something a public field, and then change it to a getter/setter later without breaking source-level compatibility. Therefore, in D I would recommend just using public fields unless you have a good reason to do otherwise. If you want to use trivial getters/setters for some reason such as only having a getter and making the variable read-only from outside the class, make them final.
Edit: For example, the lines:
S s;
s.foo = s.bar + 1;
will work for both
struct S
{
int foo;
int bar;
}
and
struct S
{
void foo(int) { ... }
int bar() { ... return something; }
}
I had exactly the same question once.
To answere it I programmed two small Programs:
The first:
#include <iostream>
class Test
{
int a;
};
int main()
{
Test var;
var.a = 4;
std::cout << var.a << std::endl;
return 0;
}
The second:
#include <iostream>
class Test
{
int a;
int getA() { return a; }
void setA(int a_) { a=a_; }
};
int main()
{
Test var;
var.setA(4);
std::cout << var.getA() << std::endl;
return 0;
}
I compiled them to assembler, with -O3 (fully optimized) and compared the two files. They were identical. Without optimization they were different.
This was under g++. So, to answere your question: Compilers easily optimize getters and setters out.