Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
340 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...