0

after declaration the pointer to int is not NULL whereas a pointer to class is NULL.

int *pint;
MyClass *Myob;
if (pint){
    cout << "pint is not null";
}
if (!Myob){
    cout << "Myob is null";
}

Why aren't pointers to Built in types and pointers to classes behaving the same way?

Akilesh
  • 1,252
  • 1
  • 9
  • 16
  • 5
    Their behavior should be undefined. You didn't initialize your pointers. This also isn't python. Objects (or pointers for that matter), by default, will not be 'false' is they're null (or nullptr in this case). They won't be anything. – DarmaniLink Jun 05 '16 at 03:36
  • 2
    Increase warning level of your compiler and treat warnings as errors. – n. m. could be an AI Jun 05 '16 at 04:38
  • In C++ you can use smart pointers and avoid a lot of problems. Use these instead – Ed Heal Jun 05 '16 at 05:18

1 Answers1

3

Nope, the pointer to both the in-built and as well as class type have indeterminate value and will lead to undefined behavior. In C or C++, if you write

int a;

or

int *b;
MyClass *c;

then a, b, c will have indeterminate value (or garbage value). If you want to initialize them as nullptr then you can declare them static (not a good approach) or initialize them explicitly as int a = 10 or int *b = nullptr.

You should always initialize pointers to NULL or nullptr (if your compiler supports C++11, assigning NULL to pointers is deprecated).

Community
  • 1
  • 1
0x0001
  • 525
  • 4
  • 12
  • 1
    You should always initialize pointers (and other variables). Sometimes `nullptr` is the appropriate initializer; other times it is not. – Pete Becker Jun 05 '16 at 11:58