Sometimes I need to expose some of the class members. For example in the following example class Mechanic
may need direct access to Engine
component. I have read many times that all fields should be accessed by mutator (accessor) methods because of several reasons. But is there any advantage when providing non-const reference getter:
class Car
{
public:
Engine & engine()
{
return m_engine;
}
//as a consequence you will also need to provide const version
const Engine & engine() const
{
return m_engine;
}
private:
Engine m_engine;
}
over simply making engine component public:
class Car
{
public:
Engine engine;
}
You can also replace public
with protected
if you don't like this example. In real life you have something simillar in Java when it comes to System.in
or System.out
. It looks like, to be fully compliant on what some people say, you would need to perform calls like System.getInstance().getOut().println("hello world")
. I don't see any benefit except a lot of bureaucratic code in such cases.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…