473,566 Members | 2,784 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

when to use "new"

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
Jul 22 '05 #1
24 2832
"Rv5" <rm*****@adelph ia.net> wrote in message
news:6a******** ************@ad elphia.com...
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
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 22 '05 #2

"Rv5" <rm*****@adelph ia.net> wrote in message
news:6a******** ************@ad elphia.com...
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
Jul 22 '05 #3
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.

"Rv5" <rm*****@adelph ia.net> дÈëÏûÏ¢ÐÂÎÅ:6a *************** *****@adelphia. com...
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

Jul 22 '05 #4
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
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

Jul 22 '05 #5
"Rv5" <rm*****@adelph ia.net> wrote in message
news:fO******** ************@ad elphia.com...
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
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 22 '05 #6
<snip>
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.creat eNew();

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

Jul 22 '05 #7
"Rv5" <rm*****@adelph ia.net> wrote in message
news:6a******** ************@ad elphia.com...
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.
Jul 22 '05 #8

"Rv5" <rm*****@adelph ia.net> wrote in message
news:fO******** ************@ad elphia.com...
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
Jul 22 '05 #9
Sam

"Gernot Frisch" <Me@Privacy.net > дÈëÏûÏ¢ÐÂÎÅ:2v *************@u ni-berlin.de...
<snip>
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.creat eNew();

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::creat eNew()
{
return new Polynomial;
}

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

??
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

Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1642
by: Yi | last post by:
Hi, I am a scientist and new to .NET programming. On my PC, I am using Windows 2000 professional with IIS, SQL Server 2000 (standard, personal), Visual Basic .net (2003, standard). By following the demo code, I can generate the web form to access the Northwind data in SQL server. When I tried to use Server Explorer to add new Data Connection...
6
2503
by: dpr | last post by:
I have come accross a piece of C++ code with the construct: MyClass *c = new class MyClass(); Is there a difference between this and: MyClass *c = new MyClass(); ?
18
8034
by: Leslaw Bieniasz | last post by:
Cracow, 28.10.2004 Hello, I have a program that intensively allocates and deletes lots of relatively small objects, using "new" operator. The objects themselves are composed of smaller objects, again allocated using "new". From my tests I deduce that a considerable part of the computational time is spent on the memory allocation, which...
4
2621
by: Ben R. | last post by:
I'm curious about the differeng behavior of the "new" keyword when dealing with value versus object types. If I'm correct, when I do: dim x as integer There's no need for "new" to be called since this "value" type is all set to go. Is this because value types are stored on the stack so the memory initialization is already taken care of? ...
3
1261
by: Ron Cook | last post by:
So I'll type something like: Dim cmd As New SqlCommand()( But for some things, it doesn't like "As New" and wants me to type like: Dim nod As employeeNode When do I know when to use "As New" as opposed to not? Intellisense always sets me straight, but I'd like to understand better.
30
3799
by: Medvedev | last post by:
i see serveral source codes , and i found they almost only use "new" and "delete" keywords to make they object. Why should i do that , and as i know the object is going to be destroy by itself at the end of the app for example: class test { public: int x;
0
1299
by: jonceramic | last post by:
Hi All, My apologies for asking something that I'm sure has been answered for. But, my google searching can't find a proper set of keywords. I would like to add "New..." or "other..." or "Show All" to my combo boxes. I'm tired of having to put buttons beside them for "special options".
12
18233
by: Jordi | last post by:
I'm getting the following error: Software error: Can't locate object method "new" via package "A::B" at /path/file.cgi line 5. My code is basically this: #!/usr/bin/perl -w use strict; use warnings; use A::B; my $test = new A::B;
3
35646
by: tvnaidu | last post by:
I compiled tinyxml files (.cpp files) and when I am linking to create final exe in Linux, I am getting lot of errors saying "undefiend reference" to "operator new" and "delete", any idea?. Main.cpp:377: undefined reference to `operator delete(void*)' tinyXML/include/tinystr.h:259: undefined reference to `operator delete(void*)'...
0
7666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8108
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7644
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7951
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1201
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.