Marcin Klima Marcin Klima - 1 year ago 84
C++ Question

Does pointers take place in memory?

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).

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download