class instantiation

S

sara

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
 
A

anon

sara said:
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.
 
?

=?iso-8859-1?q?Erik_Wikstr=F6m?=

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

Vaibhav

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

BobR

Vaibhav said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,510
Members
48,195
Latest member
Tomjerry

Latest Threads

Top