Base class iterator pointer corruption of values

I have an odd error in which if the pointer on line 46 is of the base class type and it points to the pointer stored in the vector the values become corrupted in that they have garbage. Now if the pointer is of the derived type, i.e, the second class type, the values are perfectly fine. Why is this? My original thought for this is because the pointer can't correctly store the information because of the size difference in memory. The problem with that is why is the first pointer's value, i.e, the value the first pointer has when it's initialized on line 46, correct is this undefined behavior or what is going on exactly?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <string>
#include <vector>
#include <iostream>
#include <list>
#include <memory>
using namespace std;

struct first {
	int x;
	int y;
};
struct second : public first {
private:
	bool temp;
public:
	second(int x, int y) {
		this->x = x;
		this->y = y;
	}
};
class test
{
private:
	std::vector<second> vec;
public:
	test(){}
	~test(){}
	void addnum(second num) {
		vec.push_back(num);
	}
	const std::vector<second>& getVec() const {
		return vec;
	}
};


int main()
{

	test _test;
	_test.addnum(second(314, 101));
	_test.addnum(second(666, 777));
	_test.addnum(second(42, 13));
	_test.addnum(second(1776, 1865));

	const first* it = &_test.getVec().at(0);
	for (size_t start = _test.getVec().size(); start--; it++) {
		cout << it->x << '\t' << it->y << '\n';
	}
	cout << "\n\n";

	cin.get();
	return 0;
}
The it++ uses the type to know how much it should advance the pointer. The vector is storing objects of type second so to move from one object to the next it needs to advance sizeof(second) bytes in memory. If the type of the pointer is first it will only advance sizeof(first) bytes but in this case this is not correct because it's not where the next object is stored.

vec[0]          vec[1]          vec[2]        vec[3]
|               |               |             |
[314] [101] [?] [666] [777] [?] [42] [13] [?] [1776] [1865] [?]
^           ^         ^         ^  
it          it+1      it+2      it+3
Last edited on
Topic archived. No new replies allowed.