473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

question about object instantiation

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
7 1672
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
"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

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

"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

"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
"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: thechaosengine | last post by:
Hi everyone, I've been looking at the various ways to create a data access layer recently. There was one thing in particular that occured to me and I was hoping to garner some experienced...
5
by: Gonçalo Rodrigues | last post by:
Hi all, Sorry to bother you guys again with a template question but I'm really trying to understand them and there's some piece of info that I'm missing. I'm sure I'm being really dumb here so,...
15
by: Alex | last post by:
could somebody tell me the difference between those two styles: function abc(var1, var2){ /* logic in here */ } and abc = function(var1, var2){ /* logic in here */ }; When / why would I...
12
by: mlimber | last post by:
This is a repost (with slight modifications) from comp.lang.c++.moderated in an effort to get some response. I am using Loki's Factory as presented in _Modern C++ Design_ for message passing in...
5
by: Brian | last post by:
I am "learning" C# and have run into a problem that, though I can work around it, I would like to know what the *right* way to handle the issue is. I have created an "Info" struct and assigned...
36
by: zouyongbin | last post by:
Stanley B Lippman in his "C++ Primer" that a definition like this should not appear in a header file: int ix; The inclusion of any of these definitions in two or more files of the same...
4
by: Devon Null | last post by:
I have been exploring the concept of abstract classes and I was curious - If I do not define a base class as abstract, will it be instantiated (hope that is the right word) when a derived class is...
29
by: Brad Pears | last post by:
Here is a simple OO design question... I have a Contract class. The user can either save an existing contract or they start off fresh with a blank contract, fill in the data and then save a...
2
by: Bill Gower | last post by:
I have a form that displays a list of items. The user can either click on a button called "New" to create a new item or double click on a row in the list to edit that item. An edit form is...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.