Using a vector outside a class

I have been following a tutorial which uses this code:
glm::vec4 vec(1.0f, 0.0f, 0.0f, 1.0f); // define a vector

The code works fine. However, I decided to move all my variables to a class, to better organize my code. After doing that, I got an error on the floats:
expected a type specifier

I decided then to just declare the vector in this manner:
float vec1 = 1.0f, vec2 = 0.0f, vec3 = 0.0f, vec4 = 1.0f;
glm::vec4 vec; // deffne a vector

…and then use it. However, I’m not sure how to use it.
vec(vec1, vec2, vec3, vec4);

Can someone point me in the right direction please. I’m new to opengl. Thanks.

Not sure what exactly your problem is. Seems to me that you lack some knowledge about classes in c++, or c++ in general. You should probably read some tutorials about classes.

Declaring and initializing a class member variable works a little bit different than “normal” variables, especially if you don’t use c++11 or higher (and I guess you dont). However a simple class using a glm::vector could look like this:


class A
{
public:
     A()
        : mVec{1.f,0.f,0.f,1.f}
     {}

    A(float x, float y, float z, float w)
        : mVec{x,y,z,w}
     {}


    glm::vec4 mVec;
};

You can then create an instance of this class in two different ways:


A instance1; // default constructs vector with values 1,0,0,1
A instance2(1.f,2.f,3.f,4.f); // constructs vector with values 1,2,3,4

To access the vector you use


A.mVec

But this is considered bad practice, since all members of classes should be private and not accessible directly from outside.

To use and set the values of an already existing vector, you usually (only operator overloading would make it possible) can’t do what you wrote:


vec(vec1, vec2, vec3, vec4); // won't compile

This works:


glm::vec4 vec(vec1, vec2, vec3, vec4); // this compiles

But in the latter case you are constructing an object, calling the constructor. If you want to set all the values of a vector you might have to do it this way:


glm::vec4 vec;

vec[0] = 1.f;
vec[1] = 2.f;
vec[2] = 3.f;
vec[3] = 4.f; 

I say might, because it depends on the implementation of glm which i am not familiar with. There might also be a function that let you set all 4 variables at once.
But you have to read the documentation for that.

Greetings

Seems to me that you lack some knowledge about classes in c++, or c++ in general. You should probably read some tutorials about classes.

:o

I actually just needed to keep following the manual, and not miss lines that would turn out to be important.
vec.x = blah…
vec.y = blah…
vec.z = blah…
vec.w = blah…

Thanks for your efforts though. :slight_smile: