BoringSession
BoringSession

Reputation: 83

(C++) Getter and setter in a class not working as intended

I am trying to write a simple code where the getter and setter is used.

Here is the test_class.hpp file

#ifndef TEST_CLASS_HPP
#define TEST_CLASS_HPP

class test_class
{
private:
    int num;
public:
    test_class(int num);
    ~test_class();
    int& get_num();
    void set_num(int& num);
};


#endif

Here is the test_class.cpp file

#include<iostream>
#include"test_class.hpp"

test_class::test_class(int num):num(num){};
test_class::~test_class(){};

int& test_class::get_num(){return num;}
void test_class::set_num(int& num){num = num;}

And here is the main function

#include<iostream>
#include"test_class.hpp"
#include<random>

int main(){
    test_class obj_test(69);

    int count = 10;
    while (count > 0)
    {
        std::cout << obj_test.get_num() << " at count " << count << std::endl;
        auto new_change = obj_test.get_num() - count;
        obj_test.set_num(new_change);
        count--;
    }
    
}

Aim: As count goes from 10 to 1 in the while loop, the num variable value should also decrease.

Observation: The value of num variable remains constant (initial value of 69) throughout the iteration. I played with lvalues and rvalues but I can't make it work as intended.

Upvotes: 0

Views: 583

Answers (1)

freakish
freakish

Reputation: 56467

void test_class::set_num(int& num){num = num;}

What exactly is happening here? You assign num to itself. This code does nothing. What you really want is

void test_class::set_num(int& num){ this->num = num; }

Btw you would avoid this kind of errors if you declared

void test_class::set_num(const int& num)

(or even without &) which you should do, since you don't modify num inside set_num function.

Upvotes: 3

Related Questions