-1

I'm trying to understand code below.

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

class A
{
  public :
    void Test();
};

void A::Test()
{
   ShowMessage("Hello");
}

__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
 A *x;
 x->Test();
}

I expect EAccessViolation error,when I call the Test method.

How does work without the x assign ?

İsmail Kocacan
  • 1,204
  • 13
  • 38

1 Answers1

4

How does work without the x assign ?

In theory, the posted code is cause for undefined behavior.

In practice, it works some times because A::Test() does not depend on any member data. It is not guaranteed to work in every platform.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Which platform does not work properly ? I want test it. – İsmail Kocacan Nov 06 '15 at 07:18
  • @İsmailKocacan nobody can tell you. It might work under some external circumstances on one platform like e.g. compiler switches. As R Sahu wrote: it is _undefined_ behaviour, so the compiler is free to take the phase of the moon to decide what to do here. – cdonat Nov 06 '15 at 07:23
  • @İsmailKocacan, I tested your code with VS 2008, VS 2010, and g++ 4.9.3 under cygwin. All of them worked fine. But then, that doesn't tell where it could fail. That's the hard part of **Undefined Behavior**. You don't know when you are going to be hit by a problem. – R Sahu Nov 06 '15 at 07:35