passing vector to class constructor

I have a class that has a string, an int, and then a vector of doubles all members.

my vector member is vector<double> sales;

my constructor is

myclass(string, int, vector<doubles>)

How do I pass a temporary vector from main into the class constructor?

myclass (string name, int id, vector<double> temp)

?

Is this the way it is usually done, if its even possible?
It'd just be a matter of passing your sales vector to the class:
auto myInstance = myclass(someString, someInt, sales);

Certainly one way to do it - whether it's 'usual' really depends on what's happening with the vector internally inside the class.
Thanks. So i can just pass the vector name?

And myclass object will have a vector?

Inside the class I have a function that can print out the name, id, and then all the sales inside the vector which is simple enough. just a for loop running against vec.size.

I've seen some stuff that passed vectors into functions as vec<double*> sales ? is that a pointer to a vector? I suppose that what lead to my confusion
So i can just pass the vector name?

Yes.

And myclass object will have a vector?

Yes. Be careful though. You're passing the vector by value. The class will be operating on a copy of the vector. That may be fine or not. You haven't shown enough code to tell.

I've seen some stuff that passed vectors into functions as vec<double*> sales ? is that a pointer to a vector?

No. That is a vector of pointers to doubles.



Yes. Be careful though. You're passing the vector by value. The class will be operating on a copy of the vector. That may be fine or not. You haven't shown enough code to tell.


How would I pass by reference then?
The same way as you pass any other class by reference.

As AbstractionAnon said, since we can't see what you're code is doing it's hard to tell exactly what's going on. However, I more often than not find that it's better to pass by (const, if necessary) reference. It's good to understand why and what the consequences of doing/not doing are.

Again, as AbstractionAnon alluded to, passing by value bears (potentially expensive) calls to a classes constructor/destructor.

See this example: https://ideone.com/REJqYX

And again, with a simple change to a const reference in Bar's constructor: https://ideone.com/N49pd0

Notice how we've immediately dropped unnecessary calls to Foo's copy constructor and destructor by changing one line without making any sacrifices to the code.

Whether or not Bar needs to store it's own copy of Foo, rather than just take a reference to it, is a wider design choice, depending on context (composition vs aggregation).

Hope this helps.
Last edited on
Topic archived. No new replies allowed.