0

I've been studying OOP in C++ and there are different ways to instantiate a class either through the use of the new keyword or the standard way (which doesn't use new).

Either this using new

Class *object = new Class();

or using the standard way

Class object;

I'm confused on when to use either ways. Can someone clarify on when to use or which is the preferred way to instantiate?

mmdalire
  • 11
  • 3

2 Answers2

0

In this:

Object* o = new Object

you are creating a dynamic allocation, and o is a pointer. This is usually used to save memory by referencing or as an implementation for lists and trees. The memory of the pointer must be deleted using delete because once it is out of scope the object will still exist but you will not have access, this is called a memory leak.

In the other declaration

Object o; // or Object o = Object()

You are declaring an instance of the object, not a pointer.

A pointer contains a reference of an object, not the object itself.

So answering to your question the prefered way depends but normally you'll want to use the version without new.

polmonroig
  • 937
  • 4
  • 12
  • 22
0

The new keyword is used to dynamically allocate memory. By using the new keyword, if sufficient memory is available, it initializes the memory in heap and return the address. it's then your responsibility to free memory using delete .

Otherwise, if new operator is not used, the object is automatically destroyed if goes out of scope.

LebRon
  • 755
  • 4
  • 24