1

I am working on an implementation of a simple Vector class that forms a container for a constant sized double array (following the example on page 51 of A Tour of C++). My issue is with the method int size() const. It feels odd to define it this way, instead of const int size(). Both seem to work. Does anyone know the difference, if there is any?

Below is the class declaration and the definition of Vector::size().

class Vector{

public:
    Vector(int);
    Vector(std::initializer_list<double>);
    ~Vector(){delete[] elem;}
    double& operator[](int);
    int size() const;

private:
    int sz;
    double* elem;
};

int Vector::size() const{
    return sz;
}

Note: I found similar posts (1,2), but they do not answer my question.

iamvegan
  • 482
  • 4
  • 15
  • 3
    In `const int size()` `const` is useless, you return a const temporary integer. `int size() const` says it's a `size` method which does not modifies class when called, so you can call it for const `Vector` object. – fas Apr 06 '20 at 17:24
  • 3
    const at the end means the function cannot change object members – stark Apr 06 '20 at 17:24
  • 2
    The two are entirely different. `const int size()` means that what you return shall be treated as `const` which makes little sense for a type like integer which will be returned by value. `int size() const` tells the compiler that you do not intend to modify any member of your vector. You can add a dummy member to your vector and try to assign to it in your size method using either declaration. You will see the difference. – everclear Apr 06 '20 at 17:26
  • @EduardoPascualAseff "I think it means that you can't modify the method by inheritance" - It means no such thing. It means the function returns a `const int`, nothing else. – Jesper Juhl Apr 06 '20 at 17:33
  • I learned a lot from these comments. I wish this was explained in the book too! – iamvegan Apr 06 '20 at 17:38

1 Answers1

3

Please mind that:
1. const int foo(); means: foo returns const integer value
2. int foo() const means: foo returns integer value, and doesn't modify anything.

This somehow conform with reading from right - it's please see that @2 is const function. Whereas linter in @1 will tell you that const on return value will be ignored.

pholat
  • 467
  • 5
  • 20