Where are your objects stored in C++?
Archive - Originally posted on "The Horse's Mouth" - 2010-01-16 06:36:43 - Graham EllisIf you declare a variable to be of an object type in C++ (and potentially do so with parameters), you're going to be assigning memory for the variables that it includes on the stack - i.e. within memory that will be lost when you exit the closure (block of code - function - method) in which you are defining it.
BUT if you declare a pointer to a variable of a certain type, and then fill the variable with data using the new keyword, then only the pointer to that object is in local space on the stack, and the data itself will be on the heap. This means that if you return the pointer, or copy it into a more permanent piece of storage, you will retain the data that it contains even when the original closure has been completed.
In other words, you really want to construct your objects via new most of the time, the exception being where you have an object that's only going to have a very local and limited lifetime.
The notation for accessing a method within an object uses a dot - for example:
savoy.setoccu(0.43);
and if you extend that to reference a method within an object for whcih you hold a pointer, you get the somewhat ugly form:
(*ritz).setoccu(0.76);
You're provided with "syntactic icing" in C++ to make this prettier using the -> operator instead, thus:
ritz->setoccu(0.76);
There's in example that sets up a hotel called "savoy" to hold data about a hotel, and a pointer to a hotel called "ritz" pointing to data on the heap [here]; you can find the source code of the class it uses [here] and the header file included in both [here].