Constructors etc.
Constructor is a class member with the same name as the class.
No return type
Not invoked as other methods
Automatically invoked when variable of that class instantiated
(i.e., declared). Initializers can be passed as arguments.
Only 1 default constructor per class
Multiple constructors permitted
If you don't write one, the compiler supplies a "do nothing" constructor
class_name :: class_name (param list)
{
}
Rational :: Rational(int Numer, int Denom)
{
NumeratorValue = Numer;
DenominatorValue = Denom;
}
Initialization section reduces amount of code
Rational :: Rational(int Numer, int Denom)
:NumeratorValue (Numer),
DenominatorValue (Denom)
{
}
Constructor with defaults
Rational(int = 0, int = 1);
When declaring an object
Rational r; //uses defaults
Rational s(5,6); // uses these values
Constructor can be overloaded
Multiple constructors with different types of parameters
Explicit Constructors
- Call end when declare an object of the type
- Could call explicitly as:
Rational num;
num = Rational (3,4);
- Unnecessary overhead
- Default constructor - if you don't define one, then one created for you
BUTsome types not created
For example, pointers and other classes
An example
#include <iostream.h>
class Rational {
public:
Rational(int = 0, int = 1); //constructor
Rational(long); //overloaded
Rational Add (const Rational &r);
Rational Multiply (const Rational &r);
void SetNumerator(int number);
void SetDenominator(int denom);
private:
int NumeratorValue;
int DenominatorValue;
};
void main()
{
Rational r (7.5), s (3, 4);
}