By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,385 Members | 847 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,385 IT Pros & Developers. It's quick & easy.

question about object instantiation

P: n/a
Based on my experience there is two ways to instantiate an object.

Method 1:

Car* car1 = new Car();

Method 2:

Car car1;

So, my question is what really is the difference in the two methods. Does
one get stored on the stack while the other gets stored on the heap? Is one
better than the other? How is one to reference the difference between the
two, that is is the firt method called instantiation by ? while the second
one is called instantiation by ?

Any advice is greatly appreciated,

John


Jul 22 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
On Sat, 8 May 2004 17:21:41 -0600, "johny smith"
<pr**************@charter.net> wrote:
Based on my experience there is two ways to instantiate an object.

Method 1:

Car* car1 = new Car();

Method 2:

Car car1;

So, my question is what really is the difference in the two methods. Does
one get stored on the stack while the other gets stored on the heap?
Using "new" instantiates the object "dynamically"; the area of memory where
the object is constructed happens to be called the "free store". The term
"the heap" is often used synonymously (and purists around here would be
happy to point out the differences), but those differences do not become
important unless you insist on using library functions such as malloc and
free to manage storage, rather than operators new and delete.

When you do it the other way,
Car car1;
then the object may end up just about anywhere, depending on the context of
that line of code. If it is a stand-alone definition at block scope or
namespace scope, the object ends up in automatic storage (on the stack,
usually), or static storage (a fixed location in memory, such as that
occupied by all "extern" data), respectively. If, however, the line is
part of a class definition, then it all depends on how the enclosing class
is instantiated! for example, given:

class Fleet {
Truck truck1;
Car loaners[10];
Car car1;
Bicycle b;
};

Then you might say:
Fleet f1;
Fleet *fleetp = new Fleet;

In that case, f1 is automatic (in a block) or static (namespace scope), but
the object pointed to be fleetp is dynamic (and contains a Car, among other
things.)

So as you can see, the question isn't as simple as you the one you asked.

Is one
better than the other?
Sometimes one is better than the other for some particular purpose. Time to
get yourself a good introductory C++ book and dive in.
How is one to reference the difference between the
two, that is is the firt method called instantiation by ? while the second
one is called instantiation by ?


Because the non-dynamic one can appear in different contexts, I'm not sure
how much good it would really do to label it instantiation by _____ . I
just call it creating or instantiating an object, and when using "new" I
add the word "dynamically"...
-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #2

P: n/a
"johny smith" <pr**************@charter.net> wrote in message
Method 1:
Car* car1 = new Car();

Method 2:
Car car1;
In addition to Leor's response, the 1st one invokes Car::operator new if
such a function exists. This function may utilize a pool allocator. The
entire pool of memory is created on the heap usually, so it is still heap
allocation. You also have to call delete (though a smart pointer might be a
good idea here).
So, my question is what really is the difference in the two methods. Does
one get stored on the stack while the other gets stored on the heap? Is one better than the other? How is one to reference the difference between the
two, that is is the firt method called instantiation by ? while the second
one is called instantiation by ?


As for names, how about instantiation by pointer and instantiation by value?
Be aware these terms are not in common usage.

For small objects like int, std::complex<double>, deque<T>::iterator, it's
probably faster and consumes less memory to create objects on the stack.
For larger objects, it's faster too, but the ratio of time saved is usuall
too small to worry about.

And when you need polymorphism, you have to use the 1st way. For example,
you have a class Database that holds a pointer to a Connection, but the
Connection is a derived class like MySqlConnection, OracleConnection, etc.
Jul 22 '05 #3

P: n/a

"johny smith" <pr**************@charter.net> wrote in message
news:10*************@corp.supernews.com...
Based on my experience there is two ways to instantiate an object.

Method 1:

Car* car1 = new Car();

Method 2:

Car car1;

So, my question is what really is the difference in the two methods. Does
one get stored on the stack while the other gets stored on the heap? Is one better than the other? How is one to reference the difference between the
two, that is is the firt method called instantiation by ? while the second
one is called instantiation by ?


The essential difference is the lifetime of the object.

{
Car* car1 = new Car();
} // car1 is *not* destroyed here

{
Car car1;
} // car1 is destroyed here

Neither is better, they are just different. Objects allocated with new have
an indefinite lifetime, they are only destoyed where you exlicitly use
delete. This is undoubtedly more complicated but sometimes it is what you
want.

As a newbie if you cant see why you should use new then don't. The
alternative is simpler.

john
Jul 22 '05 #4

P: n/a
johny smith posted:
Based on my experience there is two ways to instantiate an object.

Method 1:

Car* car1 = new Car();

Method 2:

Car car1;

So, my question is what really is the difference in the two methods.
Does one get stored on the stack while the other gets stored on the
heap? Is one better than the other? How is one to reference the
difference between the two, that is is the firt method called
instantiation by ? while the second one is called instantiation by ?

Any advice is greatly appreciated,

John

There is far too much talk about "new" on this newsgroup! Where do these
people learn to program?!! *This* is how you declare a variable/object:

CarClass CarObject;
In special circumstances, and only in special circumstances, you use dynamic
memory allocation! Don't put chains on your tyres when there's no snow! It
may help when there *is* snow, but without snow, ie. without the special
circumstances, it just hinders everything!

Here's a usage of "new":
void GenerateStringOfMyName(unsigned short int LengthOfName)
{
//Create an array of characters, the length of the person's name + 1
for the terminating null charachter

char NameBuffer[LengthOfName + 1];

//Long story short, the above is invalid - the amount of memory
allocated for each function must be constant!

//So you do the following:

char* pNameBuffer = new char[LengthOfName +1];

//Do some stuff

delete [] pNameBuffer;
}
You should very very rarely use "new", and even more rarely if you're not
declaring an array! Think about it, why the heck would you?!
-JKop
Jul 22 '05 #5

P: n/a

"johny smith" <pr**************@charter.net> wrote in message
news:10*************@corp.supernews.com...
Based on my experience there is two ways to instantiate an object.
Method 1:
Car* car1 = new Car();

Method 2:
Car car1;

So, my question is what really is the difference in the two methods. Does
one get stored on the stack while the other gets stored on the heap?
Method 1 heap, Method 2 stack.
Is one better than the other?
Method 2 is better because the memory that is allocated gets automatically
deleted.
How is one to reference the difference between the
two, that is is the firt method called instantiation by ? while the second
one is called instantiation by ?


Method 1 is dynamic allocation. Method 2 is static or automatic allocation.
Use method 2 whenever possible and practical. Use Method 1 only when you
have no choice (you don't know ahead of time if you will need that memory,
etc.)
Jul 22 '05 #6

P: n/a

"JKop" <NU**@NULL.NULL> wrote in message
news:Ya******************@news.indigo.ie...

You should very very rarely use "new", and even more rarely if you're not
declaring an array! Think about it, why the heck would you?!


Umm, because you're writing an Object Oriented programming exploiting
polymorphism? If you "very very rarely" use "new", then you don't write a
lot of Object Oriented code. C++ *is* an Object Oriented language,
remember?
Jul 22 '05 #7

P: n/a
"JKop" <NU**@NULL.NULL> wrote in message news:YaJnc.7338
void GenerateStringOfMyName(unsigned short int LengthOfName)
{
//Create an array of characters, the length of the person's name + 1
for the terminating null charachter

char NameBuffer[LengthOfName + 1];

//Long story short, the above is invalid - the amount of memory
allocated for each function must be constant!
I think the feature is present in standard C, and standard C++ should
eventually follow suit. Maybe someone else can comment.

//So you do the following:

char* pNameBuffer = new char[LengthOfName +1];

//Do some stuff

delete [] pNameBuffer;
Here's another reason not to use raw pointers -- if the "Do some stuff"
throws then pNameBuffer is never released. If you use

std::vector<char> pNameBuffer(LengthOfName + 1);

you're safe. So a guideline is that every use of new should use wrapped in
a smart pointer, be it std::vector<T> or std::auto_ptr or boost::shared_tpr,
so that we always destroy the object.

But when we allocate objects on the stack, we don't have to worry about
this. Plus, access to the member variables of objects on the stack is
usually faster (especially inline functions).
You should very very rarely use "new", and even more rarely if you're not
declaring an array! Think about it, why the heck would you?!


Generally I create factory/create functions which call new and return a
std::auto_ptr. The rest of the code hardly ever uses new and delete.
Jul 22 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.