Search This Blog

Saturday, November 6, 2010

Constructors

The C++ syntax defines a set of special methods called constructors. Those
methods have the same name as the class itself, and do not return results. They
are called when the variable of that type is defined :

#include
#include
class NormalizedVector
{
double x, y;
public:
NormalizedVector(double a, double b) {
double d = sqrt(a*a + b*b);
x = a/d;
y = b/d;
}
double getX() { return x; }
double getY() { return y; }
};
int main(int argc, char **argv) {
NormalizedVector v(23.0, -45.0);
cout << v.getX() << ’ ’ << v.getY() << ’\n’;
NormalizedVector *w;
w = new NormalizedVector(0.0, 5.0);
cout << w->getX() << ’ ’ << w->getY() << ’\n’;
delete w;
};

The same class can have many constructors :
#include
#include
class NormalizedVector {
double x, y;
public:
NormalizedVector(double theta) {
x = cos(theta);

y = sin(theta);
}
NormalizedVector(double a, double b) {
double d = sqrt(a*a + b*b);
x = a/d;
y = b/d;
}
double getX() { return x; }
double getY() { return y; }
};

No comments:

Post a Comment