0

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;
}

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

May I then ask why the function will run smoothly if I define aClass simply as class aClass{}; ?
Because apearing to run smoothly is one of the possible outcomes of running a program that contains undefined behaviour. Your program is ill-formed and the compiler isn't required to emit sensible code.
1
 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.