2

As per my knowledge in c++ when initializing an object with a pointer, we have to use new keyword. But in the following example the pointer is not pointing to an object initialized with 'new', but still we can call methods that do not modify member variables.

#include <iostream>
using namespace std;
class B
{
    public:

       void display()
         { cout<<"Content of base class.\n"; }

};


int main()
{
    B *b; // line p : not initialized with 'new' 

    b->display(); //line q: this prints Content of base class

    return 0;
}

In the above code I'm confused why I can call the method in line q in main method. Also why I get an error when I try to access a member variable. Thanks in advance.

  • Well, there is no access to internals of the `B` via `this`, so you got away with it. As soon as you do something in `display` with internals of the object, you'll get some memory violation – Severin Pappadeux Jan 05 '15 at 06:42

3 Answers3

2

You are invoking undefined behavior. In this case, most compilers will never attempt to access anything inside "this" and you will get away with it. But the standard does not guarantee that this will work. The code is broken.

There is more discussion here; they talk about null pointers but for our purposes a garbage pointer is nearly the same. When does invoking a member function on a null instance result in undefined behavior?

Community
  • 1
  • 1
StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
1

It works because, underneath the covers B::display() is implemented as display(B* this) and you are not doing anything with this.

If you tried to access any member variables using this->, you will see the real problem.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Its your good luck that you are able to call the non-static function without having the object intialized. In this case Pointer b is pointing some garbage and you luckily getting desired results. You will not be able to access or modify (even if they are public) data members because no memory is allocated for them

Ali Kazmi
  • 1,460
  • 9
  • 22