I'm practicing operator overloading, and my goal is to enumerate all the values of a vector class I have written myself.
In doing this I came across a segfault (no biggie) and started to pare back my code to find where it originated. After some difficulty, I've come to a point where I don't understand what's going wrong.
While trying to run a for loop to iterate over the data in a vector object, I found that I get a segfault if I use a variable s
which is set to 10. If I use the integer literal 10, it works.
This makes very little sense to me, but then again I'm working with unfamiliar concepts. Any help is appreciated!
Here's an MCVE:
Compile using g++ Q1.cpp vector.h -o Q1
Demo class (Q1.cpp):
#include <iostream>
#include "vector.h"
#define INFO(x) std::cout << "[INFO]: " << x << std::endl;
int main(void) {
// 1- Test the default constructor
INFO(" ---------- Vector 1 ----------");
vector v1;
INFO(v1);
return 0;
}
Vector class (vector.h):
#include <iostream>
#include <string>
class vector {
public:
float size;
float* data;
vector() : vector(0) {}
vector(int s){
size = s;
data = new float[size]();
}
};
std::ostream& operator<<(std::ostream& stream, const vector& obj){
stream << "vector: size(" << obj.size << ")" << "\n";
int s = 10;
for(int i = 0; i < s; ++i){ // problem occurs here, replace s with '10' and it works.
stream << i;
//stream << "data[" << i << "] = " << obj.data[i];
}
}