C++ Basics: Object Instantiation vs. Dynamic Memory Allocation

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Jan 2006
Posts: 1
Reputation: WittyFool is an unknown quantity at this point 
Solved Threads: 0
WittyFool WittyFool is offline Offline
Newbie Poster

C++ Basics: Object Instantiation vs. Dynamic Memory Allocation

 
0
  #1
Jan 24th, 2006
Quick question while learning C++:

Say you have class A, you can instantiate an object of class A like:

A a;

And then you can do stuff with that class (eg, a.method(), etc.)

But you can also do:

A a = new A();

And do stuff with that, and delete it with:

delete a;




My question: What's the difference between the two?
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,808
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 747
Team Colleague
Narue's Avatar
Narue Narue is online now Online
Code Goddess

Re: C++ Basics: Object Instantiation vs. Dynamic Memory Allocation

 
0
  #2
Jan 24th, 2006
>What's the difference between the two?
The difference is how you access the object, how long the object lives, and where it's stored.
I'm here to prove you wrong.
Reply With Quote Quick reply to this message  
Join Date: Feb 2005
Posts: 17
Reputation: kon_t is an unknown quantity at this point 
Solved Threads: 2
kon_t kon_t is offline Offline
Newbie Poster

Re: C++ Basics: Object Instantiation vs. Dynamic Memory Allocation

 
0
  #3
Jan 27th, 2006
Your code wont compile as is. What you need to have is

  1. void aFunction
  2. {
  3. A a; // create local auto object on the stack
  4.  
  5. A* ap = new A() // create object on the heap & have ap refer to it
  6.  
  7. // do something
  8.  
  9. delete ap; // manually delete object that ap refers to
  10. } // here a & ap are destroyed automatically
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC