473,770 Members | 2,143 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1694
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 "dynamicall y"; 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<do uble>, deque<T>::itera tor, 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 , OracleConnectio n, etc.
Jul 22 '05 #3

"johny smith" <pr************ **@charter.net> wrote in message
news:10******** *****@corp.supe rnews.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 GenerateStringO fMyName(unsigne d 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.supe rnews.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 GenerateStringO fMyName(unsigne d 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<cha r> pNameBuffer(Len gthOfName + 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_t pr,
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
1308
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 insight into the matter. Some people create a DA component that requires instantiation before use. For example: DataAccessComponent dac = new DataAccessComponent(connectionString);
5
288
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, please bear with me. I've reduced my problem to the following: Remark: the example below is just to highlight my problems with templates. I know very well that there are already ways of doing what the example tries to do (for example, with the...
15
417
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 use one over the other?
12
2624
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 an embedded environment with multiple processors. I created a policy for classes, which, I had hoped, would automatically register the class with the appropriate factory: // In some header file... #include <cassert>
5
1364
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 certain default values to it. I have assigned this struct to a TreeView node via the Tag field. In my "AfterSelect" processing call, I am casting the node tag value to my "Info" struct. When I look at the fields they are set to the default values...
36
3859
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 program will result in a linker error complaining about multiple definitions. So this kind of definition should be avoided as much as possible. But as we know, the definition of a class is always in a header file. And we can use "#ifndef" to eliminate...
4
1903
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 created? if ( answer == false ) { Would the idea of an abstract class simply be used to enforce integrity of the classes by disallowing the abstract class to be instantiated, or are there other purposes for it? }
29
2229
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 "new" contract. I have a method in my contract class called "Save" which is called like this... dim oContract as new Contract
2
1185
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 displayed for the add or edit and the changes are made and then the user clicks on a save or cancel button to close the form. Here is the question. Who should create the object for the form to add to or edit? Should the form with the list create an...
0
9619
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10260
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10102
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9910
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6712
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2850
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.