0

Hence this:

class A 
{ 
public: 
    A() 
    { 
        cout << "A() "; 
    } 
    void f() 
    { 
        cout << "f "; 
    } 
    ~A() 
    { 
        cout << "~A() "; 
    } 
};

int  main()
{
    A *p = (A*)2; 
    p->f(); 
}
class A 
{ 
public: 
    A() 
    { 
        cout << "A() "; 
    } 
    void f() 
    { 
        cout << "f "; 
    } 
    ~A() 
    { 
        cout << "~A() "; 
    } 
};

int  main()
{
    A *p = (A*)2; 
    p->f(); 
}
//ouput is 
// f

How can a programm call a member function of non existing object? How the programm passes the this pointer to the function?

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • 3
    Undefined behaviour. That is how. – juanchopanza Apr 24 '14 at 21:54
  • [Undefined Behavior](http://en.wikipedia.org/wiki/Undefined_behavior) – David G Apr 24 '14 at 21:55
  • So this behavior of this code is both compiler and platform dependent? – Eduard Rostomyan Apr 24 '14 at 21:56
  • 1
    Technically, it is *anything* dependent. You can get different results on the same platform and compiler. – juanchopanza Apr 24 '14 at 21:57
  • no, it's not compiler and platform dependent, it's undefined behaviour. – bolov Apr 24 '14 at 21:57
  • So accordingly, calling the function on non initialized pointer in c++ is allowed but it is undefined behavior according to ISO C++? – Eduard Rostomyan Apr 24 '14 at 21:58
  • Yes, "undefined behaviour" is typically "allowed" by the compiler/language spec (In other wrods, "the compiler is not required to detect it"). But it's undefined, so "anything can happen" - if the compiler decides to generate code to format your hard-drive as a result, then that's within the letter of the specification (if not quite within the spirit, perhaps). – Mats Petersson Apr 24 '14 at 22:01
  • 1
    @EduardRostomyan: Undefined behaviour means that you cannot derive any predictions about the program's behaviour from the rules of the language. – Kerrek SB Apr 24 '14 at 22:01
  • 1
    Try it with a `virtual` function. You'll likely get your desired explosion. As-written the compiler is simply generating a function call, pushing whatever you gave it as `this` (undefined, of course) without the need for virtual fairy dust (really, its magic =P). If you write to a member variable you'll likely get an exciting access violation with a bizarre address, and a little math will explain what is happening. Regardless, its UB. – WhozCraig Apr 24 '14 at 22:07

0 Answers0