Instantiate an Object

Hi coders,

I am learning c++ and would like your help in understanding the difference between eg.,

tcpsocket *socket = new tcpsocket
&
tcpsocket socket

the 1st expression in my novice opinion is a pointer of type tcpsocket; but what does it actually do? also the socket variable in this exprssion is a pointer which gets dynamically created from the heap and must manually be coded to destroy it after its use. Am i right about this?

the 2nd expression is creating an object of type tcpsocket and gets created on the stack. that is all i know about this expression.

please advise,

many thx tony
> the 1st expression in my novice opinion is a pointer of type tcpsocket; but what does it actually do?

The new expression creates an (anonymous) object of type tcpsocket with dynamic storage duration.


> also the socket variable in this exprssion is a pointer which gets dynamically created from the heap

The result of the new expression is a pointer to the object that was created.


> and must manually be coded to destroy it after its use. Am i right about this?

Yes; the object created by the new-expression has dynamic storage duration; it exista till the time the pointer returned by the new-expression is used in a corresponding delete-expression.


> the 2nd expression is creating an object of type tcpsocket and gets created on the stack.

It declares a (named) object of type tcpsocket with either automatic storage duration (if the statement appears within a block) or static storage duration (if the statement is at namespace scope).

More information: http://www.cplusplus.com/forum/general/161550/#msg822255
Topic archived. No new replies allowed.