954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

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

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?

WittyFool
Newbie Poster
1 post since Jan 2006
Reputation Points: 10
Solved Threads: 0
 

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

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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

void aFunction
{
       A   a;        // create local auto object on the stack

       A* ap = new A()  // create object on the heap & have ap refer to it

       // do something

      delete ap;      // manually delete object that ap refers to
}   // here a & ap are destroyed automatically
kon_t
Newbie Poster
17 posts since Feb 2005
Reputation Points: 10
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You