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 fth method is worth mentioning for
clarifying reasons:
- default constructor
- copy constructor
- value constructor
- conversion constructor
- copy assignment (not a constructor)
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
}
0 comments:
Post a Comment