[c++] Creating an object: with or without `new`

Possible Duplicate:
What is difference between instantiating an object using new vs. without

This is probably a basic question, and might have already been asked (say, here); yet I still don't understand it. So, let me ask it.

Consider the following C++ class:

class Obj{
    char* str;
public:
    Obj(char* s){
        str = s;
        cout << str;
    }
    ~Obj(){
        cout << "Done!\n";
        delete str;        // See the comment of "Loki Astari" below on why this line of code is bad practice
    }
};

what's the difference between the following code snippets:

Obj o1 ("Hi\n");

and

Obj* o2 = new Obj("Hi\n");

Why the former calls the destructor, but the latter doesn't (without explicit call to delete)?

Which one is preferred?

This question is related to c++ constructor new-operator destructor

The answer is


Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.


The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to constructor

Two constructors Class constructor type in typescript? ReactJS: Warning: setState(...): Cannot update during an existing state transition Inheritance with base class constructor with parameters What is the difference between using constructor vs getInitialState in React / React Native? Getting error: ISO C++ forbids declaration of with no type undefined reference to 'vtable for class' constructor Call asynchronous method in constructor? Purpose of a constructor in Java? __init__() missing 1 required positional argument

Examples related to new-operator

Java FileOutputStream Create File if not exists How to add to an existing hash in Ruby Expression must have class type Why should C++ programmers minimize use of 'new'? Creating an object: with or without `new` int *array = new int[n]; what is this function actually doing? Open button in new window? How to open in default browser in C# Print in new line, java Deleting an object in C++

Examples related to destructor

Is calling destructor manually always a sign of bad design? When is a C++ destructor called? How to destroy an object? How to force deletion of a python object? Creating an object: with or without `new` When should I create a destructor? How do I correctly clean up a Python object? Does delete on a pointer to a subclass call the base class destructor? Do I need to explicitly call the base virtual destructor? Dynamically allocating an array of objects