Add accessor functions to get the private member fields - C++ Class

C++ examples for Class:Member Function

Description

Add accessor functions to get the private member fields

Demo Code

#include <iostream>
using namespace std;
// declaration section
class Complex//  www  .j  a  v a 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
};   // end of declaration section
int main()
{
   Complex num1, num2(6.8, 9.7);    // declare two complex objects
   cout << "The real part of num1 is " << num1.getReal() << endl;
   cout << "The imaginary part of num1 is " << num1.getImaginary() << "\n\n";
   cout << "The real part of num2 is " << num2.getReal() << endl;
   cout << "The imaginary part of num2 is " << num2.getImaginary() << endl;
   return 0;
}

Result


Related Tutorials