I have a question regarding pointers to custom classes. Consider the below C++ fragment:
#include <iostream>
#include <vector>
class custom {
public :
int first;
custom(int x)
{
first = x;
}
};
int main() {
custom c1(1);
custom c2(2);
custom c3(3);
custom c4(4);
std::vector<custom> c;
c.push_back(c1);
c.push_back(c2);
c.push_back(c3);
c.push_back(c4);
// How can this work ?
// cp has size 2 ?
custom* cp[2];
for(int i = 0; i <= 2; ++i)
{
cp[i] = &c.at(i);
std::cout << (*cp[i]).first << std::endl;
}
return 0;
}
I create a class called custom and create 4 class objects. Next I create a pointer to the class of size 2 and assign it the address of the of the vector object.
If I print the output I would get :
1
2
3
How can a pointer of size 2 access the last index ? Is there some custom resizing going on under the hood ?
If I instead change the loop to go upto i <= 3
, it can access the last element but throws :
1
2
3
4
*** stack smashing detected ***: terminated
Aborted
My question is why doesn't the pointer throw an index out of range error and how can it access these elements ?