Passing vector to Constructor by Reference

Hi,
I want to pass vector to constructor by reference. This is mainly meant for very large size data.

My question here is:
In YourClass constructor, reference of private member myclass is directly taken. Is this right way? Though it worked well. But is this a efficient way, or taking reference in other variable and then assigning private member to it, like this. Will this increase copy memory?

public:
_YourClass(vector <MyClass> &_myclass_)
{
myclass = _myclass_;
myclass.resize(10);
}
private:
vector <MyClass> myclass;

Here is a full example:::::
////////////////////////////////////////////////////
#include <iostream>
#include <vector>
using namespace std;

class _MyClass
{
public:
_MyClass(){};
};
typedef class _MyClass MyClass;

class _YourClass
{
public:
_YourClass(vector <MyClass> &myclass)
{
myclass.resize(10);
}
private:
vector <MyClass> myclass;
};
typedef class _YourClass YourClass;

int main(int argv, char **argc)
{
vector <MyClass> myclass;
cout << "myclass.size() : " << myclass.size() << endl;
YourClass *yourclass = new YourClass(myclass);
cout << "myclass.size() : " << myclass.size() << endl;

return 0;
}

Thanks...
--
eye51
_myclass_ is a reference to myclass (the one in main()). _YourClass::myclass is a copy of myclass from main(). Do you want to make it a reference too?
it really confused us beginner.
why do you make the parameter of constructor same with the private data member
Hi,
thanks for reply.

I want to modify myclass (passed in main()) in _YourClass constructor. Then I need to modify _myclass_ in other functions of _YourClass, so I need to declare a vector in private, assign _myclass_ then modify which in turn modifies the main myclass.

Actually I tried reference operators, but it did not work. Then I finally came to pointers. This is how it worked.

public:
_YourClass(vector <MyClass> *_myclass_)
{
myclass = _myclass_;
(*myclass).resize(10);
(*myclass)[...] = ..... // way of accessing and modifying.
}
private:
vector <MyClass> *myclass;

int main()
{
vector <MyClass> myclass;
YourClass *yourclass = new YourClass(&myclass);
}

I hope this is right way of passing vector in constructor.
Please comment if any other good/efficient way is there.

Thanks.

--
eye51
I don't fully understand what you are trying to do, but I'll take a guess.

You want YourClass to modify the caller's actual parameter, right?

1
2
3
4
5
6
7
8
9
class YourClass {
    std::vector<MyClass>& myClass;

  public:
    YourClass( std::vector<MyClass>& mc ) : myClass( mc ) 
    {
         myClass.resize( 10 );
    }
};


This will be way more efficient than your first implementation (which copied the parameter, only then
to resize it down to 10 elements) and way more user friendly than your second (avoids pointers at
the cost of making YourClass copyable but not assignable).
Hi J Smith,

Thanks for your reply.
Your suggestion solved my problem.

--
eye51
Topic archived. No new replies allowed.