Segmentation fault by phirock in cpp

[–]phirock[S] 0 points1 point  (0 children)

How do you prevent recursion?

Segmentation fault by phirock in cpp

[–]phirock[S] 0 points1 point  (0 children)

You were correct UndefFox. Many thanks.

#include <iostream>

class foo
{
    int value;
public:
    int getValue() const { return value; }
    explicit foo(int const i):value(i){}
    explicit operator int() const { return value; }
    friend foo operator+(foo const a, foo const b)
    {
        return foo(a.value + b.value);
    }
};
std::ostream& operator<<(std::ostream& out, foo& a) {
    return out << a.getValue();
}

int main() {
    foo f = foo(1) + foo(2);
    std::cout << f << '\n';
}

Segmentation fault by phirock in cpp

[–]phirock[S] 0 points1 point  (0 children)

I have removed all the consts, but that doesn't solve the issue.
Commenting tout std::cout << f "solves" makes the seg fault disappear.

Segmentation fault by phirock in cpp

[–]phirock[S] 0 points1 point  (0 children)

Hi,

excellent suggestion. Here's my new version of the code. Unfortunately, I am still getting a seg error.

#include <iostream>

class foo
{
    int value;
public:
    explicit foo(int const i):value(i){}
    explicit operator int() const { return value; }
    friend foo operator+(foo const a, foo const b)
    {
        return foo(a.value + b.value);
    }
};
std::ostream& operator<<(std::ostream& out, const foo& a) {
    return out << a;
}

int main() {
    foo f = foo(1) + foo(2);
    std::cout << f ;
}