I want to dereference a vector iterator that points to a vector of class objects whose members are pointers. I'm using a compound class (class 1) whose members are pointers to another class (class 2). Class 2 has an int member variable, which I want to retrieve. If I retrieve the variable using array indexing, everything works fine. But when I try to dereference the iterator, I get a compiler error (gcc version 4.0.1 (Apple Inc. build 5465).
Here is the code (example.cpp):
Code:
//example.cpp
#include <iostream>
#include <vector>
using namespace std;
class Class1{
public:
Class1() : num(10) { /***/ }
int num;
int get_num() { return num; }
};
class Class2{
public:
Class2(Class1* C1obj) : C1ptr(C1obj) { /***/ }
Class1* C1ptr;
Class1* get_C1ptr() { return C1ptr; }
};
int main() {
int i;
Class1* C1p; //pointer to objects of class Class1
Class2* C2p; //pointer to objects of class Class2
vector<Class1> C1v(5); //vector of 5 Class1 objects (calls constructor)
vector<Class2*> C2v; //empty vector of pointers to Class2 objects
vector<Class2*>::iterator p;
//fill empty vector of type Class2 with pointers to objects whose members are of type Class1
for(i = 0; i < 5; i++) {
C1p = &C1v[i];
C2p = new Class2(C1p);
C2v.push_back(C2p);
}
//THIS WORKS PROPERLY
for(i = 0; i < 5; i++) {
cout << data[i]->get_C1ptr()->get_num() << endl;
}
//THIS CAUSES ERROR
for(p = data.begin(); p != data.end(); ++p) {
cout << *p->get_C1ptr()->get_num() << endl;
}
return 0;
}
Error message (I've tagged this as code to keep out the smileys caused by punctuation):
Code:
example.cpp: In function ‘int main()’:
example.cpp:37: error: request for member ‘get_C1ptr’ in ‘* p. __gnu_cxx::__normal_iterator<_Iterator, _Container>::operator->
[with _Iterator = Class2**, _Container = std::vector<Class2*, std::allocator<Class2*> >]()’, which is of non-class type ‘Class2*’
I could use the array indexing, but I want to understand why the iterator doesn't work. What's the proper way to dereference the iterator here?
Mike