I have a project where I draw a triangle using points, it is called Sierpinski Gasket. To achieve that I am using a class Vx which holds x and y values. The problem is it throws different values if any method is virtual and I wonder why. How virtual functions affect the way the points are generated in the following OpenGL code?
My vector class has the following declaration:
class Vx {
public:
float x;
float y;
Vx();
Vx(const float& value);
Vx(const float& x, const float& y);
Vx(const Vx& v);
float getX() const;
void setX(const float& x);
float getY() const;
void setY(const float& y);
const float operator [] (int i) const;
operator const float* () const;
operator float* ();
float& operator [] (int i);
};
std::ostream& operator<<(std::ostream& os, const Vx v);
Vx operator+(const Vx& p1, const Vx& p2);
Vx operator/(const Vx& p1, const Vx& p2);
And it's implementation is:
Vectors::Vx::Vx() : x(0), y(0)
{
}
Vectors::Vx::Vx(const float& value) : x(value), y(value)
{
}
Vectors::Vx::Vx(const float& x, const float& y) : x(x), y(y)
{
}
Vectors::Vx::Vx(const Vx& v) : x(v.x), y(v.y)
{
}
float Vectors::Vx::getX() const
{
return this->x;
}
void Vectors::Vx::setX(const float& x)
{
this->x = x;
}
float Vectors::Vx::getY() const
{
return this->y;
}
void Vectors::Vx::setY(const float& y)
{
this->y = y;
}
float& Vectors::Vx::operator[](int i)
{
return *(&x + i);
}
const float Vectors::Vx::operator[](int i) const
{
return *(&x + i);
}
Vectors::Vx::operator const float* () const
{
return static_cast<const float*>(&x);
}
Vectors::Vx::operator float* ()
{
return static_cast<float*>(&x);
}
std::ostream& Vectors::operator<<(std::ostream& os, const Vx v)
{
os << "Vx: " << "x = " << v.x << ", y = " << v.y << std::endl;
return os;
}
Vx Vectors::operator+(const Vx& p1, const Vx& p2)
{
return Vx(p1.x + p2.x, p1.y + p2.y);
}
Vx Vectors::operator/(const Vx& p1, const Vx& p2)
{
return Vx(p1.x / p2.x, p1.y / p2.y);
}
My main class starts setting up OpenGL to be ready to draw, and at some point I create a buffer with the data as following:
void sierpinskiGasket() {
using namespace Vectors;
/*
Creamos la informacion para el triangulo
*/
const int numPoints = 5000;
Vx points[numPoints];
points[0] = Vx(0.0f, 0.0f);
Vx vertices[] = {
Vx(-0.50f, -0.50f),
Vx(0.50f, -0.50f),
Vx(0.0f, 0.50f)
};
for (int i = 1; i < numPoints;i++) {
int j = rand() % 3;
points[i] = (points[i - 1] + vertices[j]) / 2;
}
/*
Generamos el buffer para el triangulo
*/
unsigned int triangle_vbo;
glGenBuffers(1, &triangle_vbo);
glBindBuffer(GL_ARRAY_BUFFER, triangle_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
}
The result I get is the next triangle (which is okay):
But if I change any method of my Vx class to virtual, the next thing happens: