Tuesday, December 2, 2014

C++ in object pro



Dynamic Memory Allocation for Objects

#include 
#include
using namespace std;
class box
{
   public:
      box() 
     { 
         cout << "Constructor called!" <<endl; 
      }
      ~box() 
      { 
         cout << "Destructor called!" <<endl; 
      }
};
int main( )
{
   box* myboxarray = new box[4];
   delete [] myboxarray; 
   return 0;
}

Calling a Function

#include 
#include
using namespace std;
int max(int num1, int num2);
 int main ()
{
             int a = 100;
   int b = 200;
   int ret;
   ret = max(a, b);
   cout << "Max value is : " << ret << endl;
    return 0;
}
int max(int num1, int num2) 
{
             int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result; 
}
 
Multiplication using addition
 
#include 
#include
int mult (int x, int y) 
{
  int result;
  result = 0;
  while (y != 0) 
 {
    result = result + x;
   y = y - 1;
  }
  return(result);
}
int main () 
{
  int x, y;
  cout << "Enter two natural numbers: ";
  cin >> x >> y;
  cout << x << " * " << y << " = " << mult(x,y) << endl;
  return(0);
}

No comments:

Post a Comment