call constructor and return object



 DEVELOP > c-Plus-Plus > call constructor and return object

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

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


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER