sooon
sooon

Reputation: 4878

c++ - passing value between classes

I have 2 classes, Qtree and Qnode:

//QuadTree.hpp:
#include <stdio.h>
#include <iostream>
#include <SFML/Graphics.hpp>

class QNode;

class QTree{
public:
    int depth;
    sf::Vector2f bound;

    QTree();

    void setRoot(QNode q);
};

class QNode{
public:
    bool isLeaf = false;
    int layer = 0;
    sf::Vector2f position;
    sf::Vector2f bound;
};

and

//Quadtree.cpp:
#include "QuadTree.hpp"

QTree::QTree(){
    bound = sf::Vector2f(100,200);
}

void QTree::setRoot(QNode q){
    q.bound = bound;
}

then in main.cpp:

#include <iostream>
#include <SFML/Graphics.hpp>
#include "QuadTree.hpp"

using namespace std;

int main(){
    QTree qt;
    QNode q;

    qt.setRoot(q);

    cout << q.bound.x <<endl;

}

and the cout result is 0. I am expecting it to be 100. I am c++ beginner and did read a lot related to this from google. However still not sure how to get this to work.

How can I resolve this?

Upvotes: 0

Views: 41

Answers (1)

Barmar
Barmar

Reputation: 780673

You need to change setRoot() so it gets the argument by reference.

void QTree::setRoot(QNode &q){
    q.bound = bound;
}

Your code is passing by value, so setRoot() modifies a copy of q.

Upvotes: 1

Related Questions