Wednesday, September 1, 2010

Types of constructors

1. Void constructors or default constructors
This has no parameters and  is must in case of dynamic allocation of objects.


2. Default parameter constructor
A default parameter is a function parameter that has a default value provided to it. If the user does not supply a value for this parameter, the default value will be used. If the user does supply a value for the default parameter, the user-supplied value is used.

3 Private constructors

4. Parametric constructor
It is good practice to try not to overload the constructors. It is best to declare only one constructor and give it default parameters wherever possible:



using namespace std;

#include <iostream>
class vector{public: double x; double y; vector (double a = 0, double b = 0) { x = a; y = b; }};int main (){ vector k; cout << "vector k: " << k.x << ", " << k.y << endl << endl; vector m (45, 2); cout << "vector m: " << m.x << ", " << m.y << endl << endl; vector p (3); cout << "vector p: " << p.x << ", " << p.y << endl << endl; return 0;}output:vector k: 0, 0vector m: 45, 2vector p: 3, 0

No comments:

Post a Comment