Can anyone tell me what the difference is between:
Display *disp = new Display();
and
Display *disp;
disp = new Display();
// 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
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 ffffd( 7 ); // prints int
sss xxx = 7; // prints double, because constructor with int is not accessible in implicit form
return 0;
}