Igor Popov
Igor Popov

Reputation: 51

Does compiler optimize this part of code (const getter)?

I have the following class definition:

class foo {
  private:
    bool m_active;

  public:
    const bool isActive() const // (btw do I need return type `const bool&` here?)
    {
       return m_active;
    }  
};
  1. Does a class with a const getter (foo->isActive()) work faster then foo->m_active (if it would be public)? I tried to look at disassembled code, but didn't find anything interesting.

  2. Where can I read about const getters and setters? I need a deep understanding as to where and why these methods are used.

Upvotes: 2

Views: 639

Answers (1)

Mysticial
Mysticial

Reputation: 471379

By default, all member functions are considered for function inlining. This means that the compiler will optimize out the entire function call and replace it with a direct access to the member.

So the answer is yes. The compiler will optimize it.

Upvotes: 8

Related Questions