//=== point/main.cpp ==============================================
. . .
Point p; // calls our default constructor
Point q(10,20); // calls constructor with parameters
Point* r = new Point(); // calls default constructor
Point s = p; // our default constructor not called.
. . .
1. No-parameter (default) constructors
* Default: If you don't declare any constructors, the compiler creates a default, parameterless constructor. Unfortunately, it does nothing good; it only satisfies the compiler's need for a parameterless constructor.
* No default: If you declare constructors with parameters, no default parameterless constructor will be created.
* Forbid creation. If you want control over creation of objects from you class (eg, to enforce use of a factory method, declare a private parameterless constructor.
* Automatically called: The parameterless constructor for class A would be called in these circumstances:
A x; // Calls default constructor
A xa = new A[99]; // Calls default constructor for each array element.
2. Copy constructors
* Purpose: To initialize one object from another. This is different than assignment because there is no pre-existing value that may have to be destroyed.
* Syntax:
A(const A& a2) {
. . .
}
Note that the parameter must be a const reference.
* Default creation. If you don't define a copy constructor, the compiler creates one which simply does a shallow memberwise copy. If you dynamically allocate memory for your class, you can only get a deep copy by writing your own copy constructor.
* Automatically called: A copy constructor is called in the following circumstances.
A x(y); // Where y is of type A.
f(x); // A copy constructor is called for value parameters.
x = g(); // A copy constructor is called for value returns.
* Preventing copying. To prevent copies, eg, to prevent an object from being passed by value, declare the copy constructor as private.
Wednesday, August 19, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment