renton01
renton01

Reputation: 79

Are the following const function equivalent?

My question is simple. I was programing a getter when I noticed that I forgot the last const in my expression. But while I was writing it, I doubted: I know that in const function you can't change the returned element, so in the second one the is const std::vector implicit?

const std::vector<int> foo() const{}
std::vector<int> foo() const{}

Upvotes: 0

Views: 69

Answers (2)

pm100
pm100

Reputation: 50190

Your concern is that if you are rturning a reference to data from within the object does that have to be const. Yes. This

class Test {
    int m_num;
public:
    int& getNum()   const { return m_num; }
};

does not compile. You need

class Test {
    int m_num;
public:
    const int& getNum()   const { return m_num; }
};

your case with a vector

class Test {
    int m_num;
    std::vector<int> m_vec;
public:
    const int& getNum()   const { return m_num; }
    std::vector<int> getVec()   const { return m_vec; }
};

works fine because you are returning a copy

but this is not ok

class Test {
    int m_num;
    std::vector<int> m_vec;
public:
    const int& getNum()   const { return m_num; }
    std::vector<int> & getVec()   const { return m_vec; }
};

has to be

class Test {
    int m_num;
    std::vector<int> m_vec;
public:
    const int& getNum()   const { return m_num; }
    const std::vector<int> & getVec()   const { return m_vec; }
};

Upvotes: 1

ChrisMM
ChrisMM

Reputation: 10105

You can return non-const values. You cannot return a non-const reference. Both of these functions return a copy, thus the const for the return type is not required.

If you were to return

std::vector<int> &

Then you would need the const.

Upvotes: 1

Related Questions