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.
They can be useful when the value you are returning is actually on the heap.
template<class T> class Singleton
{
private:
static T* m_pSingleton;
public:
T& getSingleton() { assert(m_pSingleton); return(*m_pSingleton); };
}; // eo class Singleton
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With