returning reference to a vector from a method and using its public members

Posted by memC on Stack Overflow See other posts from Stack Overflow or by memC
Published on 2010-04-27T04:51:38Z Indexed on 2010/04/27 4:53 UTC
Read the original article Hit count: 231

Filed under:
|
|

dear experts,

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;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about stdvector