Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does overloading operator<< to print Eigen class member result in a segfault?

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.

like image 773
red Avatar asked Sep 20 '18 09:09

red


People also ask

Can we overload== operator in c++?

The overloaded operator must have at least one operands of the user-defined types. You cannot overload an operator working on fundamental types.

Which operator is overloaded for cin operation?

In the statement “ cin >> head; “, cin is the first parameter and a reference to the head is the second parameter for the function. The above function is called when any such statement is executed. Overloading the ostream operator '<<': C++

Which operator can not be overloaded in c++ 1 point?

Dot (.) operator can't be overloaded, so it will generate an error.


1 Answers

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;
like image 105
P.W Avatar answered Oct 07 '22 02:10

P.W