when to use "new"

R

Rv5

Rookie c++ question, but Ive spent the last 5 years doing Java, where
everytime I created an object I used new. In c++ I can create my objects
without and its confusing me just a little.

I have a class called polynomial. Its a nothing little class right now,
with just int variables, a basic container class. Im using it as I go
through some tutorials, but in this particular tutorial its telling me to do
polynomial *first = new polynomial();
but before I found this site I was just doing
polynomial first;
Im also struggling through pointers. I understand the basics, but fail to
see the advantage using them with my objects so quickly. Is one way better
than the other?

Thanks
 
I

Ivan Vecerina

Rv5 said:
Rookie c++ question, but Ive spent the last 5 years doing Java, where
everytime I created an object I used new. In c++ I can create my objects
without and its confusing me just a little.

I have a class called polynomial. Its a nothing little class right now,
with just int variables, a basic container class. Im using it as I go
through some tutorials, but in this particular tutorial its telling me to
do
polynomial *first = new polynomial();
This seems likely to be a poor advice...
but before I found this site I was just doing
polynomial first; Right.

Im also struggling through pointers. I understand the basics, but fail to
see the advantage using them with my objects so quickly. Is one way
better than the other?
In C++, most types should be value types, behaving and used like 'int'.

Instances only should be allocated with new when they can't or shouldn't
be copied, when an object instance needs to be shared/accessed from
multiple locations, or when the lifetime of the object needs to be
explicitly controlled.

Don't use 'new' until you find out that you have to.


I hope this helps,
Ivan
 
J

John Harrison

Rv5 said:
Rookie c++ question, but Ive spent the last 5 years doing Java, where
everytime I created an object I used new. In c++ I can create my objects
without and its confusing me just a little.

I have a class called polynomial. Its a nothing little class right now,
with just int variables, a basic container class. Im using it as I go
through some tutorials, but in this particular tutorial its telling me to
do
polynomial *first = new polynomial();
but before I found this site I was just doing
polynomial first;

It's likely that you are right and the tutorial is wrong. If it works
without new then don't use it. Avoiding new leads to clearer code (because
the lifetime of the object is limited) and more efficient code (for the same
reason). Occaisionally you see code like this

{
Wotsit* w = new Wotsit();
...
delete w;
}

That's clearly rubbish because the object lifetime is exactly the same as if
w was an automatic variable.

{
Wotsit w;
...
}

The second version is exception safe too.
Im also struggling through pointers. I understand the basics, but fail to
see the advantage using them with my objects so quickly. Is one way
better than the other?

Same advice again, if you don't see the need for pointers don't use them.
They are tricky to use correctly so avoid them if you can. But I find it
surprising that you don't see the need if you have been programming Java, in
Java almost everything is a pointer.

john
 
S

Sam

Maybe you should understand what the stack is and what the heap is.
The memory for a local variable in a function (or a method of a class) is in
the stack. When the function runs, the memory for local variables are
allocated in a special memory area called the stack. Once the function
returns, the memory allocated for its local variables is free immediately
and all the values of its local variables are lost. An instance of a class
constructed in this way acts exactly like an ordinary variable such as int,
float, etc.
Now we get a problem. You can write the following Java codes:
Polynomial createNew() {
return new Polynomial();
}
the function creates a new instance of class Plynomial and returns the
reference of that new instance.

But in C++, if you write
Polynomial* createNew() {
Polynomial pn;
return &pn;
}

It doesn't work. It may be compiled and linked but actually it's very
dangerous. The instance of Polynomial is constructed when the function is
called, but also is destroyed as soon as the function returns. However, the
caller gets the pointer of that nonexistent object returned by the function
and takes it as a valid pointer.

We want a way to create new objects other than in the stack, so that we can
hold the objects even if the functions that create them return. So we get
heap. We use "new expression" to create new objects in the heap - another
special memory area where objects created by "new expressions" exist. Thus
we can write the following codes in C++:
Polynomial* createNew() {
Polynomial* ppn = new Polynomial;
return ppn;
}
Memory allocated by "new expressions" can and only can be freed by "delete"
in the C++ codes. So here comes another thing: delete anything you created
by new (after they are useless, but before you lose the pointers of them).
Unlike in Java, the system doesn't clear the useless objects created by new
here.
 
R

Rv5

I admit that with java I didnt really think of pointers that much, even
though I knew they were being used behind the scenes. I do see the value in
them, but it seems to me that they get used a lot when it isnt necessary.

That said, and back to a spin off of my original question, if I do need just
a pointer to an object and not an object itself, would i use "new" in that
case? For example:
myobject *pointer = new myobject

Just trying to figure out possible scenarios.

ross
 
I

Ivan Vecerina

Rv5 said:
That said, and back to a spin off of my original question, if I do need
just a pointer to an object and not an object itself, would i use "new" in
that case? For example:
myobject *pointer = new myobject

No, again, unless you need the lifetime of the object to extend
the current function scope.
What you would write instead is:
myobject obj;
myobject* pointer = &obj;
But I do not see in what scenario you would want to do that.

When the ownership( = responsibility to destroy) of the object
is passed to another function, it is usually better to use
a smart pointer, such as std::auto_ptr.

Also, in many uses of pointers, in C++ it is better to use
references instead (e.g. as function parameters...).


hth
Ivan
 
G

Gernot Frisch

Now we get a problem. You can write the following Java codes:
Polynomial createNew() {
return new Polynomial();
}
<snap>

Why does one want to do this:

Polynomial* p1 = OtherPoly.createNew();

instead of:
Polynomial p1 = OtherPoly;
??
I've never programmed much Java so I don't get the idea here. I think
you don't have to new/delete at all if you're from java world. If you
use container classes you have all the java functionality without
caring about new/delete. Correct me if I'm wrong.

-Gernot
 
J

Jason Heyes

Rv5 said:
Rookie c++ question, but Ive spent the last 5 years doing Java, where
everytime I created an object I used new. In c++ I can create my objects
without and its confusing me just a little.

I have a class called polynomial. Its a nothing little class right now,
with just int variables, a basic container class. Im using it as I go
through some tutorials, but in this particular tutorial its telling me to
do
polynomial *first = new polynomial();
but before I found this site I was just doing
polynomial first;
Im also struggling through pointers. I understand the basics, but fail to
see the advantage using them with my objects so quickly. Is one way
better than the other?

Thanks

Declaring pointers all over the place is no way to write C++. Only use a
pointer when you need to control the lifetime of an object.
 
J

John Harrison

Rv5 said:
I admit that with java I didnt really think of pointers that much, even
though I knew they were being used behind the scenes. I do see the value
in them, but it seems to me that they get used a lot when it isnt
necessary.

That said, and back to a spin off of my original question, if I do need
just a pointer to an object and not an object itself, would i use "new" in
that case? For example:
myobject *pointer = new myobject

Just trying to figure out possible scenarios.

ross

No, this is the common mistake. New is about the *lifetime* of the object
being created. An object created with new lives until you call delete,
that's what makes objects create with new different from automatic objects,
not pointers.

You can get a pointer to any object. If you want a pointer to an automatic
object use the & operator.

john
 
S

Sam

Gernot Frisch said:
<snap>

Why does one want to do this:

Polynomial* p1 = OtherPoly.createNew();

instead of:
Polynomial p1 = OtherPoly;

I didn't mean that createNew() is a method of class Polynomial. However, no
matter whether it is or not. It's not my point. I was just saying that, you
can easily create a new object in a function in Java and return its
handle(or reference, or pointer) to the caller so that the caller can
control that object(by calling its method). But in C++, you can't do this
easily because the object you create within a function as a local variable
is destroyed automatically after the function returns. Thus the pointer it
returns doesn't point to a valid object any longer. So you have to use the
new expression if you want an object to exist after the function that
creates it returns.
For example, suppose you have another class called MySystem, you do this in
Java:
MySystem sys = new MySystem();
Polynomial poly = sys.createNew();
It works if you have the method createNew() in class MySystem:
Polynomial createNew() {
return new Polynomial();
}

But in C++, if you write:
MySystem sys;
Polynomial* p = sys.createNew();

you must have the mothod createNew() in class MySystem as follows
Polynomial* MySystem::createNew()
{
return new Polynomial;
}

rather than
Polynomial* MySystem::createNew()
{
Polynomial po;
return &po; // oops! a bad-point-to-be
}
 
G

Gernot Frisch

Sam said:
I didn't mean that createNew() is a method of class Polynomial.
However, no matter whether it is or not. It's not my point. I was
just saying that, you can easily create a new object in a function
in Java and return its handle(or reference, or pointer) to the
caller so that the caller can control that object(by calling its
method). But in C++, you can't do this easily because the object you
create within a function as a local variable is destroyed
automatically after the function returns. Thus the pointer it
returns doesn't point to a valid object any longer. So you have to
use the new expression if you want an object to exist after the
function that creates it returns.
For example, suppose you have another class called MySystem, you do
this in Java:
MySystem sys = new MySystem();
Polynomial poly = sys.createNew();
It works if you have the method createNew() in class MySystem:
Polynomial createNew() {
return new Polynomial();
}

In C++ I'd write:

MySystem sys;
Polynomial poly; sys.CreateNew(poly); // Just set initial values

See - no new/delete required.
Avoid it where you can. It's more time efficient and if you come from
Java you don't get into memory leak trouble.

Just my .02$,
-Gernot
 
J

John Harrison

Sam said:
I didn't mean that createNew() is a method of class Polynomial. However,
no matter whether it is or not. It's not my point. I was just saying that,
you can easily create a new object in a function in Java and return its
handle(or reference, or pointer) to the caller so that the caller can
control that object(by calling its method). But in C++, you can't do this
easily because the object you create within a function as a local variable
is destroyed automatically after the function returns. Thus the pointer it
returns doesn't point to a valid object any longer. So you have to use the
new expression if you want an object to exist after the function that
creates it returns.
For example, suppose you have another class called MySystem, you do this
in Java:
MySystem sys = new MySystem();
Polynomial poly = sys.createNew();
It works if you have the method createNew() in class MySystem:
Polynomial createNew() {
return new Polynomial();
}

But in C++, if you write:
MySystem sys;
Polynomial* p = sys.createNew();

you must have the mothod createNew() in class MySystem as follows
Polynomial* MySystem::createNew()
{
return new Polynomial;
}

rather than
Polynomial* MySystem::createNew()
{
Polynomial po;
return &po; // oops! a bad-point-to-be
}

But you can simply write

Polynomial MySystem::createNew()
{
Polynomial po;
return po;
}

There is no need for pointers with all the trouble that they bring. If you
are worried about the cost of copying a Polynomial object then the answer is
to make that class efficiently copyable (by using smart pointers for
instance) not to avoid copying by introducing pointers.

john
 
S

Sam

In C++ I'd write:
MySystem sys;
Polynomial poly; sys.CreateNew(poly); // Just set initial values
It's just an example showing some differences between Java and C++. Actually
You cannot always avoid pointers in C++. Polynomial may be an abstract base
class here if I write a createNew() method for it. If I wanna just set
initial values, I should call it initPoly() something. And it is probable
that I wanna keep holding that new object after the function calling
createNew() returns.
 
S

Sam

But you can simply write
Polynomial MySystem::createNew()
{
Polynomial po;
return po;
}

There is no need for pointers with all the trouble that they bring. If you
are worried about the cost of copying a Polynomial object then the answer
is to make that class efficiently copyable (by using smart pointers for
instance) not to avoid copying by introducing pointers.

john
Yes. You're right. But may I argue that you need pointers for polymorphism
at least. "References" in c++ are more confused than pointers, I think.
 
H

Howard

John Harrison said:
It's likely that you are right and the tutorial is wrong.


Hello...? Did it occur to you that the purpose of that particular tutorial
might be to *teach* using pointers? One does not learn how to use pointers
by avoiding them.

Pointers are useful in many situations, but they are most often useful when
storing polymorphic objects in containers. That is, storing pointers to
base class objects in a vector (for example), when those pointers actually
point to dynamically created instances of derived class objects. Of course,
that's something you wouldn't tackle until later, if you're just starting on
pointers, but it's an example of where they are commonly used.

All that said, I do agree that if you don't actually *need* pointers, don't
bother using them. You'll find out soon enough if there's a case where you
*do* need a pointer. (And just because a function you're calling requires a
pointer as a parameter, doesn't mean that you have to pass it a pointer
variable...you more likely want to pass the address of an existing object.)

At some point, you'll also want to look at using "smart" pointers. They
really help make code better in those cases where you *do* need pointers.

-Howard
 
G

Gernot Frisch

At some point, you'll also want to look at using "smart" pointers.
They really help make code better in those cases where you *do* need
pointers.

....depending on what you call "better" code. But, I agree, there's
situations where smarties are more appropreate than simple pointers...
-Gernot
 
R

Rv5

Thanks for all the info guys. Lot to absorb. Im going to have to read each
post carefully, maybe ever a couple times to really grab what is going on
here. C++ is definitely a lot more indepth then java is.
 
K

Karl Heinz Buchegger

Rv5 said:
Thanks for all the info guys. Lot to absorb. Im going to have to read each
post carefully, maybe ever a couple times to really grab what is going on
here. C++ is definitely a lot more indepth then java is.

Honestly. Not a good idea.
A better idea is to get a book. There are so many pitfalls and
things to know in C++, that you can't discover them on your own
without major frustration.
 
D

DaKoadMunky

Only use a
pointer when you need to control the lifetime of an object.

What if the type of object to be created is not known until run-time?

What if the number of objects to be created is not known until run-time?

At the lowest level I believe the new operator would be required.

Of course at a higher level one could use abstractions to avoid having to
explicitly use new and delete.
 
J

Jason Heyes

DaKoadMunky said:
What if the type of object to be created is not known until run-time?

Such an object has it's lifetime managed by the programmer. What's your
point?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,181
Messages
2,570,970
Members
47,537
Latest member
BellCorone

Latest Threads

Top