944,081 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 15477
  • C++ RSS
Jan 24th, 2006
0

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

Expand Post »
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?
Similar Threads
Reputation Points: 10
Solved Threads: 0
Unverified User
WittyFool is offline Offline
1 posts
since Jan 2006
Jan 24th, 2006
0

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

>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.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Jan 27th, 2006
0

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

Your code wont compile as is. What you need to have is

C++ Syntax (Toggle Plain Text)
  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
Reputation Points: 10
Solved Threads: 2
Newbie Poster
kon_t is offline Offline
17 posts
since Feb 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: path
Next Thread in C++ Forum Timeline: Not home work help but very ver simple





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC