tags:

views:

81

answers:

2

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;
}
+2  A: 

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.

Billy ONeal
thanks billy. I tried using arrow operator. The code compiles, but val1 prints some garbage value (should print 10 instead) About avoiding public members: Do you mean making t_vec private and ony returning its members to outside classes by get* methods?.. if so, will do so, but still interested in how to resolve this issue... thanks again
memC
+5  A: 

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!

Max
While I agree the second line is strange, that should not affect the output of the program itself.
Billy ONeal
when you write b = B() the following occures:Suppose that at the right part there is created temporary object b_2Then there is operator = which is embedded in c++ (but you can redefine it! than it will work normally). The operator = makes b.t1 = b_2.t1. But just after that, b_2 is dying, so your pointer b_2.t1 is deleted, and b.t1 is also becomes bad pointer.
Max
oops! Thank you very much guys, That resolved the issue! Also, if you have any comments on returning the vector itself (e.g. any better design you can think of ) please let me know!
memC
@Max: Oops. +1 (afdasfdasdfafd character limit)
Billy ONeal