Problems with getters and setters in C++

377 Views Asked by At

I have a problem with my getters and setters in C++. I implemented a Queue, I also implememented a class Process. My queue saves processes. My class Process has two attributes: "Identifier" and "Time" and also has setters and getters. I set 80 as its Time. The problem then is that I want to modify the time to 50 and it doesn't change. I think that the problem is the Queue, but I don't know where. Heres is my fragment of code

Queue<Process> process;
Process x;
x.setIdentifier("Hi");
x.setTime(80);
process.enqueue(x);
process.getElementFront().setTime(50);
process.print();

Here is my Queue code:

class Queue{
private:
    int size;
    Node <L> *front;
public:
     .
     .
     .
    //front()
    
    L getElementFront() const{
        return this->front->getElement();
    }
    

Here is my Node code:

class Node{
private:
    L elem;
    Node *next;
public:
    .
    .
    .
    L getElement() {
        return this->elem;
    }

This is my Process Class:

class Process{
private:
    string identifier;
    int time;
public:
    Process(){
        identifier = "";
        time = 0;
    }
    string getIdentifier(){
        return identifier;
    }
    int getTime(){
        return time;
    }
    void setTime(int time){
        this->time = time;
    }
    void setIdentifier(string identifier){
        this->identifier = identifier;
    }
    
    friend ostream &operator<<(ostream &o, const Process &p);
    
  };
  ostream &operator<<(ostream &o, const Process &p){
    o<<"Identifier: "<<p.identifier<<"\n";
    o<<"Time:"<<p.time<<"\n";
  return o;
  }

The output of the first code is: Time = 80. I should be Time = 50, but time wasn't modified.

1

There are 1 best solutions below

1
On

I believe your function "getElementFront" returns a copy of your element, So your queue will never be affected. You can write a function like "setElementFront(int)" to affect the element directly or something like this.