Add mutator function to change class member field value - C++ Class

C++ examples for Class:Member Function

Description

Add mutator function to change class member field value

Demo Code

#include <iostream>
using namespace std;
// declaration section
class Complex/* w ww  .ja  va 2 s .  c  o  m*/
{
   private:
   double realPart;
   double imaginaryPart;
   public:
   Complex(double real = 0.0, double imag = 0.0)  // inline constructor
   {
      realPart = real;
      imaginaryPart = imag;
   }
   double getReal() {
      return realPart;
   }            // inline accessor
   double getImaginary() {
      return imaginaryPart;
   }   // inline accessor
   void setReal(double rl) {
      realPart = rl;
   }
   void setImaginary(double im) {
      imaginaryPart = im;
   }
};
int main() {
   Complex num1(16.4,18.9);    // declare a Complex object
   cout << "The real part of num1 is " << num1.getReal() << endl;
   cout << "The imaginary part of num1 is " << num1.getImaginary() << "\n\n";
   num1.setReal(25.2);
   num1.setImaginary(-27.8);
   cout << "The real part of num1 is now " << num1.getReal() << endl;
   cout << "The imaginary part of num1 is now " << num1.getImaginary() << endl;
   return 0;
}

Result


Related Tutorials