Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

invalid use of non-static data member

Here is my code:

#include <iostream>
#include <memory>
#include <vector>

class var {
private:
    double value_;
    std::shared_ptr<var> left_;
    std::shared_ptr<var> right_;

public:
    var(const double& v) : value_(v){};

    friend var operator+(const var& l, const var& r) {
        var result(l.value_ + r.value_);
        left_ = std::make_shared<var>(l.value_);
        right_ = std::make_shared<var>(r.value_);
        return result;
    }

    friend std::ostream& operator<<(std::ostream& os, const var& var) {
        os << var.value_;
        return os;
    }
};

int main() { var a(1); }

The error I am getting is as follows:

test.cpp: In function ‘var operator+(const var&, const var&)’:
test.cpp:17:9: error: invalid use of non-static data member ‘var::r_’
   17 |         r_.push_back(std::make_shared<var>(l.value_));
      |         ^~
test.cpp:10:39: note: declared here
   10 |     std::vector<std::shared_ptr<var>> r_;
      |                                       ^~

I am struggling to understand why I am getting the error in the title.
Is there a workaround?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your friend var operator+ is not a member of the class.
In order to access data members it should specify the instance.

Therefore change:

  left_ = std::make_shared<var>(l.value_);
  right_ = std::make_shared<var>(r.value_);

To:

//vvvvvvv---------------------------------------
  result.left_ = std::make_shared<var>(l.value_);
  result.right_ = std::make_shared<var>(r.value_);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading