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());
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first case:
Does three things:
disp, with the typeDisplay*, that is, a pointer to an object of typeDisplay, and thenDisplayobject on the heap, anddispvariable to point to the newDisplayobject.In the second case:
You create a variable
dispwith typeDisplay*, and then create an object of a different type,GzDisplay, on the heap, and assign its pointer to thedispvariable.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:
and
However, because of the way C type rules work, there is a difference between:
and
Because in that last case
disp1is a pointer to aDisplayobject, probably allocated on the heap, whiledisp2is 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.