Friday, November 28, 2014

C++ Class constructor pro



A simple program demonstrating C++ class

 
#include 
#include
using namespace std;
class cl 
{
  int i; 
public:
  int get_i();
  void put_i(int j);
};
int cl::get_i()
{
  return i;
}
void cl::put_i(int j)
{
  i = j;
}
int main()
{
  cl s;
  s.put_i(10);
  cout << s.get_i() <
  return 0;
}

Constructor

 
#include 
#include
using namespace std;
class Box
{
  public:
    double length;
    double breadth;
    double height;
    Box(double lengthValue, double breadthValue, double heightValue)
    {
      cout << "Box constructor called" << endl;
      length = lengthValue;
      breadth = breadthValue;
      height = heightValue;
    }
    double volume()
    {
      return length * breadth * height;
    }
};

Using inline initialization in constructor

 
#include 
#include
using namespace std;
class Box
{
  public:
    double length;
    double breadth;
    double height;
    Box(double lv = 1.0, double bv = 1.0, double hv = 1.0):length(lv),
              breadth(bv),height(hv)
    {
      cout << "Box constructor called" << endl;
    }
       double volume()
    {
      return length * breadth * height;
    }
};
int main()
{
  Box firstBox(80.0, 50.0, 40.0);
  double firstBoxVolume = firstBox.volume();
  cout << endl;
  cout << "Size of first Box object is "
       << firstBox.length  << " by "
       << firstBox.breadth << " by "
   << firstBox.height
       << endl;
  cout << "Volume of first Box object is " << firstBoxVolume
       << endl;
  return 0;
}

Copy constructor 

 
#include 
#include 
using namespace std;
class myclass 
{
  int *p;
public:
  myclass(int i);
  ~myclass();
  int getval() { return *p; }
};
myclass::myclass(int i)
{
  cout << "Allocating p\n";
  p = new int;
  if(!p) 
 {
    cout << "Allocation failure.\n";
    exit(1); 
  }
 
  *p = i;
}
myclass::~myclass()
{
  cout << "Freeing p\n";
  delete p;
}
void display(myclass ob)
{
  cout << ob.getval() << '\n';
}
int main()
{
  myclass a(10);
  display(a);
  return 0;
}

Destructor 

 
#include 
#include
#include 
using namespace std;
class myclass 
{
  int *p;
public:
  myclass(int i);
  ~myclass();
  int getval() { return *p; }
};
myclass::myclass(int i)
{
  cout << "Allocating p\n";
  p = new int;
  if(!p) 
 {
    cout << "Allocation failure.\n";
    exit(1); 
  }
  *p = i;
}
myclass::~myclass()
{
  cout << "Freeing p\n";
  delete p;
}
void display(myclass &ob)
{
  cout << ob.getval() << '\n';
}
int main()
{
  myclass a(10);
 
  display(a);
 
  return 0;
}

No comments:

Post a Comment