C++ Function Parameter pass by value for custom object

Introduction

Attempting to change the value of an object in a function, fail when the object is passed by value

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

class Employee/*from  w w w.  ja  v  a  2  s . c  om*/
{
  public:
    int  workHour;
    double salary;
};

void myFunction(Employee copyS)
{
    copyS.workHour = 10;
    copyS.salary           = 3.0;
    cout << "The value of copyS.salary = " <<copyS.salary<<endl;
}

int main(int argc, char* pArgs[])
{
    Employee s;
    s.salary = 0.0;

    cout << "The value of s.salary = " << s.salary << endl;

    cout << "Calling myFunction(Employee)" << endl;
    myFunction(s);
    cout << "Returned from myFunction(Employee)" << endl;

    cout << "The value of s.salary = " << s.salary << endl;

    return 0;
}



PreviousNext

Related