Home > OS >  Are the following const function equivalent?
Are the following const function equivalent?

Time:03-26

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{}

CodePudding user response:

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.

CodePudding user response:

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; }
};
  •  Tags:  
  • c
  • Related