11

For the following struct

struct TestClass {
  TestClass() : mat(Eigen::Matrix3i::Zero()) {}
  Eigen::Matrix3i mat;
};

I would like to have an overloaded operator<< to print the mat member to std::cout. I tried

std::ostream& operator<<(std::ostream& out, const TestClass& object) {
    out << object.mat;
}

This results in a segfault. Can anyone explain to me why?

A minimum working example:

#include <iostream>
#include <Eigen/Core>

struct TestClass {
  TestClass() : mat(Eigen::Matrix3i::Zero()) {}    
  Eigen::Matrix3i mat;
};

std::ostream& operator<<(std::ostream& out, const TestClass& object) {
  out << object.mat;
}

int main() {
  TestClass testObject;

  std::cout << testObject.mat << "\n\n"; // This works fine.
  std::cout << testObject << '\n'; // This results in a segfault.

  return 0;
}

I'm compiling with g++ version 7.3.0 and Eigen version 3.4 on Ubuntu 18.04.

red
  • 195
  • 1
  • 10
  • 10
    You must return the `std::ostream` reference from the operator overload implementation, e.g. `return out << object.mat;`. Non-void functions not returning anything are usually tagged with some compiler warnings, it might be worth enabling these (e.g. `-Wall -pedantic`). – lubgr Sep 20 '18 at 09:11

1 Answers1

14

The return value of the overloaded operator<< is std::ostream&. However, you are not returning anything from it.

Do the following:

out << object.mat;
return out;

or alternatively,

return out << object.mat;
john
  • 85,011
  • 4
  • 57
  • 81
P.W
  • 26,289
  • 6
  • 39
  • 76