By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,131 Members | 1,812 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,131 IT Pros & Developers. It's quick & easy.

class instantiation

P: n/a
Hi,

Assume we have a class called A. Assume it has a constructor which
takes an integer as its input. What is the difference between these
two instantiations?

A a(1);
and
A a=new A(1);

Thanks.
Sara

Jun 4 '07 #1
Share this Question
Share on Google+
4 Replies


P: n/a
sara wrote:
Assume we have a class called A. Assume it has a constructor which
takes an integer as its input. What is the difference between these
two instantiations?

A a(1);
and
A a=new A(1);
The difference is the first is allowed, and the second will give you
syntax error, because your object should be a pointer to initialize it
like that.
Jun 4 '07 #2

P: n/a
On 4 Juni, 11:51, sara <sarasar...@gmail.comwrote:
Hi,

Assume we have a class called A. Assume it has a constructor which
takes an integer as its input. What is the difference between these
two instantiations?

A a(1);
and
A a=new A(1);
Consider the following code:

void test()
{
A foo(1);
A* bar = new A(1);
}

In this case both will create a new instance of an object of type A,
but foo will be destroyed as soon as test() returns, because it's
lifetime is limited by the scope in which it was created. bar on the
other hand will continue to exist until you use 'delete' to destroy
it, its lifetime is not limited.

In general you should use the first type when you can and the second
when you must.

--
Erik Wikström

Jun 4 '07 #3

P: n/a
In the first step, you are creating a local object whereas in the
second step (assuming you have missded A*) you are creating object
pointer.

The local object will be destroyed as soon as you get out of function
where A a(1) is defined whereas the pointer will linger until you call
delete A.

Hope this makes it clear.

Jun 4 '07 #4

P: n/a

Vaibhav <va***********@gmail.comwrote in message...
In the first step, you are creating a local object whereas in the
second step (assuming you have missded A*) you are creating object
pointer.
The local object will be destroyed as soon as you get out of function
where A a(1) is defined whereas the pointer will linger until you call
delete A.
Hope this makes it clear.
Makes WHAT clear?

Please read this before your next post:
http://www.parashift.com/c++-faq-lite/how-to-post.html

Jun 4 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.