1

Hell'o, I have a class with member veriable which is pointer. If I create an instance of this class without initialize member pointer (pointing some memory or null - whatever), will this pointer take place in memory? For instance - I'm goin' to create button instance, but user can decide either it has sound effect on click or it doesn't - So button class should not reserve memory for sound (if user had have chosen that).

Marcin Klima
  • 451
  • 1
  • 5
  • 9

2 Answers2

6

It will reserve memory for the pointer itself, but not for the object that the pointer would point to.

In this case, you should assign the pointer the value of nullptr (or NULL if you're using C++03 or earlier) in your constructor for the object, though I would consider changing the design so that this is unnecessary (eg having two classes for button-with-sound and button-without-sound and using some form of inheritance). Assigning nullptr is a convenient value to check if the pointer is actually pointing to anything or not, and on modern desktop systems also has the effect of making a crash much more likely if you incorrectly access it (though it doesn't actually guarantee it). A crash is better than your program doing something weird and unexpected, possibly involving corrupting data, that will take you forever to track down!

The space taken up for the pointer itself will be quite small (likely 8 bytes on 64-bit Intel architectures but this is not guaranteed of course).

Muzer
  • 774
  • 4
  • 11
0

At the low level, a pointer in C is really an integer. The compiler just allows you to do more with them than you can with integers, but you can cast pointer to integer and vice versa.

So, yes, your pointer takes up space in memory (the size of an integer, probably 4 bytes on 32-bit, 8 bytes on 64-bit).

If you don't like that, you should find a different design.