0

I have started writing a really basic tile engine in C++ and I'm not entirely sure when to use const return values. Should I use them in cases like this

class A
{
    private:
        Rectangle hitBox;

    public:
        A();
        const bool Collision(const Rectangle& hitBox2);
};

or is it totally pointless?

3
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by firstPerson
0

The const return value in that example is pointless and does nothing. The time to use const return value is when the method is returning a reference or pointer to one of it's data items, assuming you don't want the calling function to change the value.

class foo()
{
public:
   const int& foo(int index)
   {
      return items[index];
    }
private:
   vector<int> items;
}

Put const after the function name is a different matter, it means the function changes nothing. For example, the following is an error.

class foo
{
public:
    foo() {}

    bool bar() const
    {
        x = 1;  // <<<<< Error because function is const
        return true;
    }
private:
    int x;
};

Edited by Ancient Dragon

0

If you are returning by value on built in type, don't return it constant. It might confuse the user, but its arguable. See here

Edited by firstPerson

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.