Add accessor function to read member field - C++ Class

C++ examples for Class:Member Function

Description

Add accessor function to read member field

Demo Code

#include <iostream>
using namespace std;
// declaration section
class Complex/*w w w . j a v a2  s.c  om*/
{
   private:
   double realPart;
   double imaginaryPart;
   public:
   Complex(double real = 0.0, double imag = 0.0)   // inline constructor
   {
      realPart = real;
      imaginaryPart = imag;
   }
   void showComplexValues();                       // accessor prototype
   void assignNewValues(double real, double imag)  // inline mutator
   {
      realPart = real;
      imaginaryPart = imag;
   }
   Complex multScaler(double = 1.0);
};
void Complex::showComplexValues()   // accessor
{
   char sign = '+';
   if (imaginaryPart < 0)
      sign = '-';
   cout << realPart << ' ' << sign << ' ' << abs(imaginaryPart) << 'i';
}
Complex Complex::multScaler(double factor)
{
   Complex newNum;
   newNum.realPart = factor * realPart;
   newNum.imaginaryPart = factor * imaginaryPart;
   return newNum;
}
int main()
{
   Complex complexOne(12.57, 18.26), complexTwo;  // declare two objects
   cout << "The value assigned to complexOne is ";
   complexOne.showComplexValues();
   complexTwo = complexOne.multScaler(10.0);  // call the function
   cout << "\nThe value assigned to complexTwo is ";
   complexTwo.showComplexValues();
   return 0;
}

Result


Related Tutorials