0

I'm reading this book and I'm having trouble understanding some of the code that's written in it. The program is supposed to function as a basic database for a company. It should have employee objects that contain their salary, status in company (hired/fired) and have some methods that you can call on that object to update it.

This is the code they provide

#pragma once

#include <string>

namespace Records {
    const int kDefaultStartingSalary = 30000;

    class Employee
    {
    public:
        Employee();

        void promote(int raiseAmount = 1000);
        void demote(int demeritAmount = 1000);
        void hire(); // Hires or rehires the employee
        void fire(); // Dismisses the employee
        void display() const;// Outputs employee info to console

        // Getters and setters
        void setFirstName(const std::string& firstName);
        const std::string& getFirstName() const;

        void setLastName(const std::string& lastName);
        const std::string& getLastName() const;

        void setEmployeeNumber(int employeeNumber);
        int getEmployeeNumber() const;

        void setSalary(int newSalary);
        int getSalary() const;

        bool getIsHired() const;

    private:
        std::string mFirstName;
        std::string mLastName;
        int mEmployeeNumber;
        int mSalary;
        bool mHired;
    };
}

I can't seem to understand why on the setFirstName and setLastName they are passing in by reference in the parameters, then in other setters/getters (like setSalary) they are passing by value. If someone could explain why this is good practice, that'd be excellent! They didn't explain their choice in the book.

1 Answers1

0

Passing by reference means you don't have to make a copy of the data in memory, just for the function call, since you're only sending the address of it, so you're using the original data (that's also why you might want to make it a const reference). For a simple variable, it doesn't really matter in the sense of performance, but with larger objects, it's faster to avoid having to make a copy of it.

A basic assumption to start with is that it's a good idea to use references for object, and values for variables. But in some cases, it really depends on a lot of other things. For example, if the function is going to do a lot of heavy calcuation, and you've got a reference to some object, which might be anywhere in memory, then you might get cache misses that will cost you performance. So there are a lot of possible things to consider for different situations. But a priori, the rule.of.thumb to use references for objects and by-value for variables is an overall good approach.

antiHUMAN
  • 250
  • 2
  • 11