Dfsgfdgh Fgfdhgfhgh Dfsgfdgh Fgfdhgfhgh - 1 month ago 6x
C++ Question

C++ Pointing to classes

I'm going through a C++ book at the moment and i'm slightly confused about pointing to classes.

Earlier in the book the examples used classes and methods in this way:

Calculator myCalc;

while( myCalc.run() ){

However, now it's changed to doing it this way:

Calculator* myCalc = new Calculator;
myCalc -> launch();

while( myCalc -> run() ){
myCalc -> readInput();
myCalc -> writeOutput();

And I can't seem to find an explanation in there as to WHY it is doing it this way.

Why would I want to point to a class in this way, rather than use the standard way of doing it?

What is the difference? And what circumstances would one or the other be preferable?

Thank you.


First, you are not pointing to the class, but to an instance of the class, also called an object. (Pointing to classes is not possible in C++, one of its flaws if you'd ask me).

The difference is the place where the object is allocated. When you're doing:

Calculator myCalc;

The whole object is created on the stack. The stack is the storage for local variables, nested calls and so on, and is often limited to 1 MB or lower. On the other hand, allocations on the stack are faster, as no memory manager call is involved.

When you do:

Calculator *myCalc;

Not much happens, except that a Pointer is allocated on the stack. A pointer is usually 4 or 8 bytes in size (32bit vs. 64bit architectures) and only holds a memory address. You have to allocate an object and make the pointer point to it by doing something like:

myCalc = new Calculator;

which can also be combined into one line like shown in your example. Here, the object is allocated on the heap, which is approximately as large as your phyiscal memory (leaving swap space and architectural limitations unconsidered), so you can store way more data there. But it is slower, as the memory manager needs to kick in and find a spare place on the heap for your object or even needs to get more memory from the operating system. Now the pointer myCalc contains the memory address of the object, so it can be used with the * and the -> operators.

Also you cannot pass pointers or references to objects on the stack outside their scope, as the stack will get cleaned when the scope ends (i.e. at the end of a function for example), thus the object becomes unavailable.

Oh and nearly forgot to mention. Objects on the heap are not automatically destroyed, so you have to delete them manually like this*:

delete myCalc;

So to sum it up: For small, short living objects which are not to leave their scope, you can use stack based allocation, while for larger, long living objects the heap is usually the better place to go.

*: Well, ideally, not like that. Use a smart pointer, like std::unique_ptr.