Reputation: 301
This is probably just something I don't understand about c++, but why does this code give me a runtime error? If I don't initialize someInt2 or I don't specify that aClass has an int member, I don't get the error.
using namespace std;
class aClass
{
int someint;
public:
aClass()
{
someint=4;
}
};
int bFunc()
{
return 4;
}
aClass aFunc()
{
aClass class1=aClass();
return class1;
}
int main()
{
int * someInt2;
*someInt2=bFunc();
aClass * thisClass;
cout << "Got here" << endl;
*thisClass=aFunc();
cout << "Not here" << endl;
return 0;
}
Upvotes: 0
Views: 105
Reputation: 146940
int * someInt2;
*someInt2=bFunc();
Undefined behaviour. You didn't make someInt2
point anywhere meaningful.
Edit: "Appearing to function correctly" is one of the possible things that "undefined behaviour" can be.
Upvotes: 1
Reputation: 21351
int * someInt2;
is an uninitialised pointer, and yet you are trying to assign a value to what it points to. You need to allocate some memory or simply use a int
variable to store the return value of the function.
Upvotes: 1