How is obj1 is referenced and calling show method if it is NULL

Viewed 76

I am trying to create the class that can only allow one object to be created at a time, so i have created private constructor and one public wrapper getInstance() method that will create object for this class, the code goes as follows

#include <iostream>
using namespace std;
class sample
{
    static int cnt;
    int temp;
    private: sample()
    {
        //temp++;
        cnt++;
        cout<<"Created "<<++temp<<endl;
    }
    public:
    void show()
    {

        cout<<"Showing \n";
    }

    static sample* getInstance()
    {
        cout<<"count is "<<cnt<<endl;
        if(cnt<1)
            return (new sample());
        else
            return NULL;
    }

};
int sample::cnt=0;
int main()
{
   // cout<<"Hello World";
    sample *obj = sample::getInstance();
    obj->show();

    sample *obj1 = sample::getInstance();
    if(obj1 == NULL)
        cout<<"Object is NULL\n";
    obj1->show();

    return 0;
}

How is obj1->show() is getting called?
OUTPUT :

count is 0
Created 1
Showing
count is 1
Object is NULL
Showing
2 Answers

In a vacuum, this is just because your function:

public:
void show()
{

    cout<<"Showing \n";
}

don't actually try to do anything with the object - to get into the correct mindset of why this works just think of a member function as an abstraction over a free function taking the object as it's first argument:

void show(Object* this)
{

    cout<<"Showing \n";
}

Now it is easy to see why this works since you don't use this - the null pointer.

If you change to something ala. this:

public:
void show()
{

    cout<< this->temp << "Showing \n";
}

Your program should almost certainly crash.

What is almost certainly happening here is that the compiler is optimizing the call to show by inlining it. Further, it can also make it a "pseudo-static" function, as the there is no reference inside show to any other class member.

To 'break' the optimisation (and cause a crash) you can do one of these:

  1. Decare the show function virtual
  2. Reference a non-static member (e.g. temp) inside the function
Related