Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to provide non-const reference getter

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.

like image 878
mip Avatar asked Nov 06 '10 15:11

mip


1 Answers

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
like image 192
Moo-Juice Avatar answered Sep 17 '22 23:09

Moo-Juice