user399540
user399540

Reputation: 279

C++ operator used when creating a new object

I have a question about the way objects are created in C++. If I define a class, say CSomeClass, I can create a new object of CSomeClass using the following line:

CSomeClass* pSomeClass = new CSomeClass;

and in this case I also have the ability to control the way the new object is created by overriding new operator. My question is, when I use the following line of code

CSomeClass pSomeClass;

What operator is being used to create the object in this case. I'd like to be able to override that particular operator in the same manner that I can the new operator but I'm not sure which that would be. If this question doesn't quite make sense, please let me know and I'll clarify. Thanks.

Upvotes: 1

Views: 897

Answers (4)

haberdar
haberdar

Reputation: 511

CSomeClass* pSomeClass = new CSomeClass;

Here you create a dynamic object of the class CSomeClass. The compiler calls the no-argument constructor.

CSomeClass pSomeClass;

You create non-dynamic object of the class CSomeClass. The compiler calls EXACTLY the same no argument constructor.

You can use operator new to allocate memory for dynamic variables:

int *number= new int(1);

Upvotes: 0

Krzysztof Kozielczyk
Krzysztof Kozielczyk

Reputation: 5937

If you want to create the creation of the object, you want to create a default constructor, not override the new operator.

In your header file:

class CSomeClass
{
public:
    CSomeClass();
}

And then in your definition file:

CSomeClass::CSomeClass()
{
    // Initialize your object here
}

That is, unless I misunderstood the question :-)

Upvotes: 0

Todd Gardner
Todd Gardner

Reputation: 13521

It doesn't make sense to be able to override the latter. The "new" operator is override-able to allow optimizations in allocating, for instance, using a slab allocater, etc. But when you create a variable on the stack, there is no decision to be made as to where it is placed.

Upvotes: 2

Georg Fritzsche
Georg Fritzsche

Reputation: 98984

In the second case, no operator is involved. There is nothing to override.

Upvotes: 3

Related Questions