steph
steph

Reputation: 333

Class Object Not Modifying Other Class Object Correctly

I am trying to create a Model class that does the following: - creates a Mesh class instance - calls the addVertex function of the created Mesh object - calls the addTriangle function of the created Mesh object

The Mesh class has two vectors to which the functions add to but when I print the contents in main.cpp they are empty.

Here is my code:

Model Class:

class Model 
{
public:
    /*  Model Data */
    /...

    //using default constructor

    Mesh createMesh() {
        Mesh mesh;
        meshes.push_back(mesh);
        return mesh;
    }

    void addVertex(Mesh mesh, Vertex v) {
        mesh.addVertex(v);
    }
    void addTriangle(Mesh mesh, Vertex a, Vertex b, Vertex c) {
        mesh.addTriangle(a,b,c);
    }
/...

Mesh Class:

class Mesh {
public:
    /*  Mesh Data  */
    vector<Vertex> vertices;
    vector<unsigned int> indices;
    /...
// constructor
    Mesh(vector<Vertex> vertices, vector<unsigned int> indices, vector<Texture> textures)
    {
        this->vertices = vertices;
        this->indices = indices;
        this->textures = textures;
        for (Vertex v: vertices) {
            pairings.insert( std::pair<Vertex,unsigned int>(v,count) );
            count++;
        }
        setupMesh();
    }
    Mesh () {

    }

    //function 1
    void addVertex(Vertex vertex) {
        vertices.push_back(vertex);
        pairings.insert( std::pair<Vertex,unsigned int>(vertex,count));
        count++;
    }

    //function 2
    void addTriangle(Vertex a, Vertex b, Vertex c) { 
        unsigned int index = pairings[a];
        indices.push_back(index);
        index = pairings[b];
        indices.push_back(index);
        index = pairings[c];
        indices.push_back(index);
        setupMesh();
    }

main.cpp:

Model m;
    Mesh mesh = m.createMesh();
    Vertex a;
    a.Position = glm::vec3 (-1,0,0);
    m.addVertex(mesh, a);
    Vertex b;
    b.Position = glm::vec3 (0,1,0);
    m.addVertex(mesh,b);
    Vertex c;
    c.Position = glm::vec3 (1,0,0);
    m.addVertex(mesh,c);
    m.addTriangle(mesh,a,b,c);
    std::cout << mesh.indices.size(); //prints 0


Any help would be greatly appreciated!

Upvotes: 1

Views: 32

Answers (1)

Frost2779
Frost2779

Reputation: 126

I believe it is because on your addVertex and addTriangle methods within your Model class, you are passing the parameters by value, not by reference or pointer. This means that when you call the method you will pass a copy of your Mesh and Vertex objects and any changes you make inside the method will be lost as soon as execution of the method is complete. Try the following changes:

void addVertex(Mesh &mesh, Vertex &v) {
    mesh.addVertex(v);
}
void addTriangle(Mesh &mesh, Vertex &a, Vertex &b, Vertex &c) {
    mesh.addTriangle(a,b,c);
}

For more information on passing by reference, please refer to the following.

Upvotes: 2

Related Questions