Cannot understand the output of this program

974 views c++
-1

#include <iostream>
using namespace std;

class A{
  private : static A *ob;
  public : static A* fun1();

  public : void show(string str){
     cout<<"This is :- "<<str<<endl;
  }
};

A* A::ob=NULL;

A* A::fun1(){
  if(ob==NULL){
     ob=new A();
     return ob;
  }
  return NULL;
}


int main() {
   A *ob1 = A::fun1();
   A *ob2 = A::fun1();

   ob1->show("A");    // line 1

   ob2->show("B");   //line 2

   return 0;
}

the output is :-

This is :- A
This is :- B

Although i expected only "This is :- A" since 'ob2' is NULL and dereferencing it should give error.

Can someone explain the output?

answered question

@Fureeish If i replace line1 and line 2 by if(ob1!=NULL) ob1->show("A"); // line 1 if (ob2!=NULL) ob2->show("B"); //line 2 then why i get expected output, since ob2 in not NULL ?

This looks like an attempt of implementing singleton, except A::fun() should always return ob and never NULL. The idea is that if ob is NULL it will instance ob so it stops being NULL, and if ob is already instanced then it will just return it.

Its very similar to singleton but what i tried to implement is that if an object of a class is already created then on creating another object it should report error !

Well that's not reporting anything, maybe you should use throw std::runtime_error("object already exists"); or something like that.

2 Answers

0

Dereferencing NULL is undefined behaviour (Why dereferencing a null pointer is undefined behaviour?), and so is invoking a non-static member function through NULL: When does invoking a member function on a null instance result in undefined behavior?

That means you can’t rely on any behaviour, not even a crash. On many platforms this will crash, but your described output is just as valid.

posted this
10

ob2->show("B"); does not dereference NULL. What it does is call the method with a null this pointer. However, since the method never refers to a member variable, it never dereferences the null this pointer.

posted this

Have an answer?

JD

Please login first before posting an answer.