Can anyone tell me what the difference is between:
Display *disp = new Display();
and
Display *disp; disp = new Display();
and
Display* disp = new Display();
and
Display* disp(new Display());
The first case:
Display *disp = new Display();
Does three things:
disp
, with the type Display*
, that is, a pointer to an object of type Display
, and thenDisplay
object on the heap, anddisp
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.
// implicit form // 1) creates Display instance on the heap (allocates memory and call constructor with no arguments) // 2) creates disp variable on the stack initialized with pointer to Display's instance Display *disp = new Display(); // explicit form // 1) creates Display instance on the heap (allocates memory and call constructor with no arguments) // 2) creates disp variable on the stack initialized with pointer to Display's instance Display* disp(new Display()); // 1) creates uninitialized disp variable on the stack // 2) creates Display instance on the heap (allocates memory and call constructor with no arguments) // 3) assigns disp with pointer to Display's instance Display *disp; disp = new Display();
Difference between explicit and implicit forms of initialization will be seen only for complex types with constructors. For pointer type (Display*) there is no difference.
To see the difference between explicit and implicit forms check out the following sample:
#include <iostream> class sss { public: explicit sss( int ) { std::cout << "int" << std::endl; }; sss( double ) { std::cout << "double" << std::endl; }; // Do not write such classes. It is here only for teaching purposes. }; int main() { sss ddd( 7 ); // prints int sss xxx = 7; // prints double, because constructor with int is not accessible in implicit form return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With