Reputation: 11960
I actually come from Java side, so am having a little bit of confusion in learning C++.
One thing I've seen is that many tutorials describe new
as an operator. In Java, I usually use that keyword to instantiate classes, i.e., create objects from the class like this.
MyObject mo = new MyObject();
I knew that it can also be used to allocate dynamic memory like as with int* a = new int;
but, I'm not getting why this is called as a operator. Am of the opinion that operators are symbols that are used to perform mathematical operations, that too, in between the operands. However, new isn't used in between operands, as per my basic understanding.
Can anyone please clarify me why this is called as an operator?
Thanks.
Upvotes: 5
Views: 188
Reputation: 25459
The semantics of new
in Java and C++ are actually quite similar. In both languages, statements like
Object o = new Object(); // Java
or
Object * optr = new Object(); // C++
Object
Object
passing it a pointer to the newly allocated memory as the this
pointer.In Java, some more magic happens behind your back but let's put that aside for now.
The semantics for built-in types (primitives in Java) are also not dramatically different.
In Java
int[] array = new int[42];
allocates memory large enough to hold 42 int
s and initializes them with 0.
In C++
int * array = new int[42]; // not value-initialized
also allocates (on the free store) contiguous memory large enough to hold 42 int
s but does not initialize them. If you want value-initialization, say so explicitly:
int * array = new int[42](); // initialized to 0
The biggest difference is perhaps how these operators are used. In Java, if we want a new object, we have no chance but calling (perhaps via some indirection through a factory method) new
. In C++, we can not only create objects on the free store (heap) but also with so-called automatic storage duration (ie push them on the stack). In Java, this is only possible with primitive types.
int i = 7; // valid in both languages
std::string name("Mona Lisa"); // valid C++, invalid Java
Often times, this is what you should do in C++. It is a common mistake of programmers who are used to Java and learn C++ to use new
all over the place where it is really not needed.
Finally, since C++ by default has no garbage collector, if you allocate memory from the free store (using operator new
), you must also free it again (using operator delete
) once you need it no longer.
Why are new
and delete
called operators? I don't know. Does it really matter? I think it makes sense, especially since you can overload them just like operator +
or -
.
The syntax of object creation in C++ used to be a bit messy. All these are (sometimes) valid but look quite differently:
// automatic storage
int a = 7;
std::string name; // default constructor
std::string name("Mona Lisa");
// free store (bad idea in this case)
std::string * nameptr = new std::string(); // default constructor
std::string * nameptr = new std::string("Mona Lisa");
There are a number of rules about which of these notations is valid in which context and if you forget, some rather strange surprises can happen.
Since C++11, we have a unified syntax for object creation using initializer-lists:
// automatic storage
int a {7};
std::string name {} // default constructor
std::string name {"Mona Lisa"};
// free store (bad idea in this case)
std::string * nameptr = new std::string {}; // default constructor
std::string * nameptr = new std::string {"Mona Lisa"};
Unfortunately, since the old syntax is still valid, we have now even more alternatives.
Upvotes: 1
Reputation: 727137
I am of the opinion that operators are symbols that are used to perform mathematical operations, that too, in between the operands
That is true only of binary infix operators. There are also unary operators that take a single operand (numeric negation; logical negation), parenthesized postfix operators (square brackets, parentheses), and parenthesized prefix operators (conversion) in C++.
Considering such multitude of operators in C++, it should come as no surprise that new
is also an operator. It is a prefix keyword operator that operates on a type name, and produces a pointer to an instance of that type. The operator has several forms, too: in addition to the regular new
, there is a placement new
operator, which has a slightly different syntax.
Upvotes: 4
Reputation: 31455
C++ isn't Java. In Java operators cannot be overloaded.
In C++ they can and there is a syntax to do so. To overload new
in C++ you use the word operator
before it. There is also operator new[]
which can be overloaded.
I presume it makes it stand out as not being a function, even though it might look like one, i.e. it takes arguments of a size and returns void *.
You can overload class member new
and delete
too as well as new[]
and delete[]
. (Strangely operator new
for a class still takes as an argument a number of bytes, which seems strange as it has to be the size of the class, so you might think it could be implied).
Upvotes: 0
Reputation: 22385
Due to the distinction between primitives and objects in C++, "operator" has two meanings. The first meaning is close to what you describe in your question: operators perform some specific operation on their primitive arguments like addition or memory allocation as defined by the standard.
But when used with objects, operators work completely different: they call their corresponding member function of the class. For example !
which does boolean negation of primitives, calls the bool operator !()
function of an object. File streams in C++ redefine the !
function to test if an error has occurred in the stream.
new
is an operator because it similarly calls a member function (and can be redefined! Though I've never seen anyone do that).
Upvotes: 1
Reputation: 59841
What does it mean to be an operator? In programming languages operators
are constructs which behave like functions but differ semantically or syntactically from normal functions.
In C++ operators are semantically special in that they can be overloaded and their arguments must match specific requirements. Obviously their syntax is also special.
new
meets all those requirements.
Upvotes: 0