I have run into this situation where I need to constantly pass a vector around. The ideal idea is to pass it by reference so the program doesn't slow down from constantly copying the vector.
class Bar has the original vector.
Bar.h:
#ifndef Bar_h
#define Bar_h
#include <iostream>
#include <vector>
using namespace std;
class Bar{
public:
Bar();
vector<int> & getVec();
private:
vector<int> vec;
};
#endif
Bar.cpp:
#include <iostream>
#include "Bar.h"
using namespace std;
Bar::Bar(){
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
}
vector<int> & Bar::getVec(){
return vec;
}
Class foo receives the vector.
foo.h:
#ifndef Foo_h
#define Foo_h
#include <iostream>
#include <vector>
using namespace std;
class Foo{
public:
Foo();
private:
vector<int> & vecRef;
};
#endif
foo.cpp:
#include <iostream>
#include "Foo.h"
#include "Bar.h"
using namespace std;
Foo::Foo(){
Bar bar;
vecRef = bar.getVec();
}
main:
#include <iostream>
#include "Foo.h"
using namespace std;
void main(){
Foo foo();
}
The problem is that when compiling I get Error code C2758 which stats "a member of reference type must be initialized". It is referring to the foo class and vector<'int> & vecRef; not being initialized properly. My question is how would I go about properly initializing vecRef while keeping its declaration in foo.h? (i have done it successfully by declaring vecRef in foo.cpp, but that's not what i want if possible). OR is adding the '&' into vector<'int> & vecRef; not the way to go about this at all?
Foo();constructor must initialize the referencevecRefin a member initializer list. It's not possible withoutBarpassed as a constructor parameter or being a member variable ofFoo.