The first case:
Display *disp = new Display();
Does three things:
- It creates a new variable
disp, with the type Display*, that is, a pointer to an object of type Display, and then
- It allocates a new
Display object on the heap, and
- It sets the
disp variable to point to the new Display object.
In the second case:
Display *disp; disp = new GzDisplay();
You create a variable disp with type Display*, and then create an object of a different type, GzDisplay, on the heap, and assign its pointer to the disp variable.
This will only work if GzDisplay is a subclass of Display. In this case, it looks like an example of polymorphism.
Also, to address your comment, there is no difference between the declarations:
Display* disp;
and
Display *disp;
However, because of the way C type rules work, there is a difference between:
Display *disp1;
Display* disp2;
and
Display *disp1, disp2;
Because in that last case disp1 is a pointer to a Display object, probably allocated on the heap, while disp2 is an actual object, probably allocated on the stack. That is, while the pointer is arguably part of the type, the parser will associate it with the variable instead.