mercredi 13 octobre 2021

getter setter c++ not as expected

i want to ask about getters/setters. i have 2 classes besides 'main'. I get an error when accessing a variable from a different class.

this is my code

#include <iostream>
using namespace std;

class Employee {
  private:
    // Private attribute
    int salary;

  public:
    // Setter
    void setSalary(int s) {
      salary = s;
    }
    // Getter
    int getSalary() {
      return salary;
    }
};

class boss {
  public: 
  void tes() {
    Employee myObj;
    cout << "(2) boss ask salary:  " << myObj.getSalary() << "?\n";

    myObj.setSalary(60000);
    cout << "(3) boss said new salary:  " << myObj.getSalary() << "\n";
  }
};

int main() {
  Employee myObj;
  myObj.setSalary(50000);
  cout << "(1) main said salary: " << myObj.getSalary() << "\n";

  boss bs;
  bs.tes();

  return 0;
} 

and output:

(1) main said salary: 50000
(2) boss ask salary:  32649?
(3) boss said new salary:  60000

why is the result in line 2 not as expected? should be 50000. How do I write the code to make it correct? thank you.

Aucun commentaire:

Enregistrer un commentaire