C++: Multiple Constructors
Although up until now I've told you that you can only have one constructor, that is a lie.
You can in fact overload constructors, by simply having different parameters in each one.
I think this demonstrates the point quite well:
#include <iostream>
using namespace std;
class ClassOne{
private:
int energy;
int speed;
int endurance;
public:
ClassOne(){
Setattributes(0, 0, 0);
}
ClassOne(int e){
Setattributes(e, 0, 0);
}
ClassOne(int e, int s){
Setattributes(e, s, 0);
}
ClassOne(int e, int s, int en){
Setattributes(e, s, en);
}
void Setattributes(int energy, int speed, int endurance){
this->energy = energy;
this->speed = speed;
this->endurance = endurance;
}
void PrintAttributes(){
cout << "Energy " << this->energy << "\nSpeed " << this->speed << "\nEndurance " << this->endurance << endl << endl;
}
};
int main(){
ClassOne Object(12);
Object.PrintAttributes();
ClassOne Object2(12, 22);
Object2.PrintAttributes();
ClassOne Object3(12, 22, 63);
Object3.PrintAttributes();
system("PAUSE");
return 0;
}
All it does is use the correct constructor depending on how many parameters the user has entered.
Then for the values that user hasn't entered it simply fills them in as 0.
Overloading constructors is often very useful, and can be used in many situations.
Back to C++

