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?

Recommended Answers

All 2 Replies

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

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.