I got segmentation faults when I run the codes below. I noticed that the segmentation fault occurs when I reach another.print(), but I could not figure out why. Can anyone please help?
example.h
class X
{
private:
struct Y{
int a;
Y* next;
} *head;
public:
X();
X(int k);
X returnX() const;
void print() const;
};
example.cpp
#include <iostream>
#include "test.h"
X::X(){
head = nullptr;
}
X::X(int k){
head = new Y;
head->a = k;
head->next = nullptr;
}
X X::returnX()const
{
X test{};
return test;
}
void X::print() const
{
cout << "a = "<< head->a << endl;
}
int main(){
X* init = new X(1);
X another = init->returnX();
another.print();
delete init;
return 0;
}