| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"Tarscher" |
| Date: |
31 Jan 2008 06:24:35 AM |
| Object: |
call constructor and return object |
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
.
|
|
| User: "Alf P. Steinbach" |
|
| Title: Re: call constructor and return object |
31 Jan 2008 06:54:02 AM |
|
|
* 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
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
.
|
|
|
|

|
Related Articles |
|
|