call constructor and return object

T

Tarscher

hi all,

I have a scripting and c# background and want to know how I

I have a vector containing a selfmade object

I want to add elements to that vector
vector<MyClass> object;
object.push_back(/*what do I do here*/)

In c# I could do
object.push_back(new MyClass())

But how do I call the constructor in c++ and return the object to the
vector?

Regards,
Stijn
 
A

Alf P. Steinbach

* Tarscher:
hi all,

I have a scripting and c# background and want to know how I

I have a vector containing a selfmade object

I want to add elements to that vector
vector<MyClass> object;
object.push_back(/*what do I do here*/)

In c# I could do
object.push_back(new MyClass())

But how do I call the constructor in c++ and return the object to the
vector?

Depends whether you want objects directly in the vector, which means
putting an object in the wonder is a copying operation, or whether you
want pointers to objects.

For objects directly in the vector you can do

vector<MyClass> objects;
objects.push_back( MyClass() ); // Default-construct and copy.

For pointers you can do like

typedef boost::shared_ptr<MyClass> PMyClass;
vector<PMyClass> objects;
objects.push_back( new MyClass );

The point of using boost::shared_ptr<MyClass> instead of just MyClass*
is that the smart pointer takes care of destruction and deallocation,
whereas with raw pointers in the vector you'd have to do that yourself.
You can find the Boost stuff at the Boost pages.

Cheers & hth.,

- Alf
 

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

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,967
Members
47,516
Latest member
TobiasAxf

Latest Threads

Top