next up previous
Next: How do I initialize Up: class and struct Previous: How do I use

How do I create an instance of a class?

The methods called when a class is created are called contructors. There are four possible ways of specifying constructors; the fifth method is worth mentioning for clarifying reasons:

struct A
{
  A() { /* ... */ }                          // default constructor 
  A(const A &a) { /* ... */ }                // copy constructor 
  A(int i, int j) { /* ... */ }              // value constructor 
  A     &operator=(const A &a) { /* ... */ } // copy assignment 
};

struct B
{
  B() { /* ... */ }           // default constructor
  B(const A &a) { /* ... */ } // conversion constructor 
};

void	function()
{
  A	a0(0, 0); // shortcut, value constructor 
  A	a1(a0);   // shortcut, copy constructor 
  B	b1(a1);   // shortcut, conversion constructor 
  B	b;        // shortcut, default constructor 

  b1 = a0;        // conversion contructor 
  a0 = a1;        // copy assignment 
}



Alexis Angelidis (PhD) 2005-01-11