-2

This might be a newbie question, but I am asking myself it anyway.

If I have a Object class defined:

Object *p = new Object();

Does this code create a pointer p, and at location p, place a Object object, correct?

towi
  • 21,587
  • 28
  • 106
  • 187
Samuel French
  • 665
  • 3
  • 11
  • 22
  • see this http://en.wikipedia.org/wiki/New_(C%2B%2B) – Sanish May 15 '13 at 05:05
  • 1
    I think the downvotes are because you don't show any research. You can find a lot of information on a lot of webpages, including wikipedia as liked by Sanish, but also in any [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?rq=1), [tutorial](http://www.cplusplus.com/doc/tutorial/) or [reference webpage](http://en.cppreference.com/w/). – leemes May 15 '13 at 05:44
  • If my answer solves your problem, please don't forget to mark it as accepted. It will ease searching for the answer for those, who come later. – Spook May 17 '13 at 11:43

1 Answers1

3

This means:

  • Prepare a variable for an address to Parent class and name it p
  • Allocate enough memory to store contents of a Parent class
  • Call the constructor of a Parent class
  • Store address of that memory in variable p.

Edit: In response to comment:

This is not the only way to construct a class. The other one is to allocate a class statically, eg.

Parent p;

In such case you don't store a pointer to the Parent class in variable p, but the whole class itself. In such case:

  • Memory for the class is located on the stack in a frame reserved for function, which defines this variable (stack is allocated only once, when program is loaded into memory)
  • Constructor is called automatically, when program reaches point of declaration of the variable.
  • Destructor is called automatically, when program leaves the scope of this variable
  • No memory is deallocated (at least none for instance of Parent class), because stack is reused later.
Spook
  • 25,318
  • 18
  • 90
  • 167