Declare the instance variable for a class : Instance « Class « C++






Declare the instance variable for a class

Declare the instance variable for a class
  

#include <iostream>
using namespace std;

class Power {
  double b;
  
  int e;
  
  double val;
public:
  Power(double base, int exp);
  
  double getPower() { 
     return val; 
  }
};

Power::Power(double base, int exp)
{
  b = base;
  e = exp;
  val = 1;
  if(exp == 0) 
     return;
  for( ; exp > 0; exp--) 
     val = val * b;
}

int main()
{
  Power x(4.0, 2), y(2.5, 1), z(5.7, 0);

  cout << x.getPower() << " ";
  cout << y.getPower() << " ";
  cout << z.getPower() << endl;

  return 0;
}
           
         
    
  








Related examples in the same category

1.Construct object in an object array one by one
2.Loop through an object array and call its method
3.class array and object method call