Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Returning a class variable

When I try using a method to return a private variable, it seems the value changes from since the object was constructed. Here is my code and output.

main.cpp

#include <iostream>
#include "coordinate.h"

using namespace std;

int main()
{
    Coordinate c(1, 1);
    cout << c.getX() << endl;

}

coordinate.cpp

#include "coordinate.h"
#include <iostream>

using namespace std;

Coordinate::Coordinate(int x, int y)
{
    x = x;
    y = y;

    cout << x << endl;

}

coordinate.h

#ifndef COORDINATE_H
#define COORDINATE_H

class Coordinate
{
    private:
        int x;
        int y;

    public:
        Coordinate(int x, int y);

        int getX() { return x; }
        int getY() { return y; }
};

#endif

Output

like image 490
Brennan Hoeting Avatar asked Feb 13 '26 15:02

Brennan Hoeting


1 Answers

Your constructor is assigning to its arguments instead of the object's private fields. Use an initialization list, or explicitly qualify the assignment targets with this, or pick different argument names:

Coordinate::Coordinate(int x, int y) : x(x), y(y) {
    cout << x << endl;
}

or

Coordinate::Coordinate(int x, int y) {
    this->x = x;
    this->y = y;
    cout << x << endl;
}

or

Coordinate::Coordinate(int xVal, int yVal) {
    x = xVal;
    y = yVal;
    cout << x << endl;
}
like image 92
user2357112 supports Monica Avatar answered Feb 16 '26 04:02

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!