returning reference to a vector from a method and using its public members
Question
I have a vector t_vec
that stores references to instances of class Too
. The code is shown below. In the main
, I have a vector t_vec_2 which has the same memory address as B::t_vec
.
But when I try to access t_vec_2[0].val1 it gives error val1 not declared
.
Could you please point out what is wrong? Also, if you know of a better way to return a vector from a method, please let me know! Thanks in advance.
class Too {
public:
Too();
~Too(){};
int val1;
};
Too::Too(){
val1 = 10;
};
class B {
public:
vector<Too*> t_vec;
Too* t1;
vector<Too*>& get_tvec();
B(){t1 = new Too();};
~B(){delete t1;};
};
vector<Too*>& B::get_tvec(){
t_vec.push_back(t1);
return t_vec;
}
int main(){
B b;
b = B();
vector<Too*>& t_vec_2 = b.get_tvec();
// Getting error
std::cout << "\n val1 = " << t_vec_2[0].val1;
return 0;
}
Solution
You have 2 errors: The first was already said, you should write
t_vec_2[0]->val1
instead of
t_vec_2[0].val1
The second is the strange line b = B();
I think you should delete it. The error occurs because right part B() is gonna be delete just after it is created. So you don't get in the object b the 10 value as you want. Just delete this line and it'll be ok!
OTHER TIPS
But when I try to access t_vec_2[0].val1 it gives error val1 not declared.
That's because your vector is holding pointers, not Too
objects. Replace the dot (.
) operator with the arrow (->
) operator, like this:
std::cout << "\n val1 = " << t_vec_2[0]->val1;
As a general rule though, you should probably avoid having public members at all.