invalid use of non-static data member

Here is my code:

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

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

    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?

>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_);


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

Leave a Reply