Home > Net >  C const class member function abs()
C const class member function abs()

Time:08-22

Intro

I'm currently working on a implementation of a 'mathematical' vector, like in MATLAB, since I'd like to learn more about C . The Vector class has some constructors (including a copy constructor that is shown below), some operators (including a copy operator, shown below) and some methods (only relevant method shown):

template <class T = double>
  class Vector {
  public:
    Vector(Vector<T>& vec) : vector_(vec.vector_), size_(vec.size_) {}

    // ... some other constructors ...

    Vector<T>& operator=(const Vector<T>& other) {
      if (this != &other) {
        vector_ = other.vector_;
        size_ = other.size_;
      }
      return *this;
    }

    // ... some other operators, etc. ...

    Vector<T> abs() {
      Vector<T> result = *this;
      for (std::size_t i = 0; i != length(result); i  ) {
        result.vector_[i] = fabs(result.vector_[i]);
      }
      return result;
    }

  private:
    std::vector<T> vector_;
    std::array<std::size_t, 2> size_{0, 0};
  };

FYI: fabs() comes from #include <cmath>.

Now I'm currently working on abs(), a element wise absolute value method.

Problem

Since abs() does NOT change the object itself, it could be made const like this:

Vector<T> abs() const { ... }

but, apparently this does not work and I get the following errors:

error: binding reference of type 'Vector<int>&' to 'const Vector<int>' discards qualifiers
       Vector<T> result = *this;

note:  initializing argument 1 of 'Vector<T>::Vector(Vector<T>&) [with T = int]'
       Vector(Vector<T>& vec) : vector_(vec.vector_), size_(vec.size_) {}

Can anyone tell me what the problem is?

CodePudding user response:

This is because your copy constructor cannot accept const reference. In this line

Vector<T> result = *this;

Copy constructor of Vector<T> is called. But when you mark your member function as const, this is also considered to be a const pointer. And when dereferencing you get const reference to *this, which you try to bind to non-const reference in your copy constructor. The solution is to make your copy constructor accept const reference

Vector(const Vector<T>& vec) : vector_(vec.vector_), size_(vec.size_) {}

As a general rule, you should accept arguments by const reference if you are not going to change them in the function. Copy constructor usually(in almost all cases) doesn't modify the object from which copying takes place.

  • Related