Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, on object creation, is new used implicitly?

Tags:

c++

oop

When I create an object of a class, say,

class A {
  public: A() {}
};

A a;

Is only the constructor called? Or is it that the new operator is used implicitly?

Like we have to do A* b = new A();

Also, where will a and b be stored in memory? Stack or heap?

like image 965
h4ck3d Avatar asked Aug 20 '12 18:08

h4ck3d


People also ask

What is the use of new operator?

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

Can objects be created in C?

In C++, an object is created from a class. We have already created the class named MyClass , so now we can use this to create objects. To create an object of MyClass , specify the class name, followed by the object name.

What is the use of the new keyword in C++?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.

Why do we create object in C?

To use the data and access functions defined in the class, you need to create objects.


1 Answers

In the first case, if a is not a global variable, then it will be put on the stack, while b will be put on the heap.

And in the first case, only the constructor is called. new is never called except if you do it explicitly as in the second case.

like image 156
Some programmer dude Avatar answered Sep 25 '22 16:09

Some programmer dude