How do you have and use more than one constructor for a class?
Printable View
How do you have and use more than one constructor for a class?
Just keep adding them:Code:class MyClass {
public:
MyClass() { m_iVal = 5; }
MyClass(int iVal) { m_iVal = iVal; }
protected:
int m_iVal;
};
void main() {
MyClass x; // x.m_iVal = 5
MyClass y(32); // y.m_iVal = 32
}
Ah, ok. I guess I am just used to Java classes. Anyway, thanks.
Code:class MyClass {
public:
MyClass() { m_iVal = 5; }
MyClass(int iVal) { m_iVal = iVal; }
protected:
int m_iVal;
};
void main() {
MyClass x = new MyClass(); // x.m_iVal = 5
MyClass y = new MyClass(32); // y.m_iVal = 32
}
"Ah, ok. I guess I am just used to Java classes. Anyway, thanks."
It's the same thing in Java........
public class MyClass{
double x, y, width, height;
MyClass(double y, double x, double width, double height){
this.y = y;
this.x = x;
this.width = width;
this.height = height;
}
MyClass(int y, int x,){
this(x,y,10,10);
}
MyClass(){
this(1,1);
}
}
~~~ this is a special notation provided by java to enable you to
invoke a constructor of the same class from another constructor of that class. commonly refered to as a constructor call satatement.
you don't need to overload the constructor if you don't pass different types or in different orders, you can use default values:
MyClass(int iVal=5) { m_iVal = iVal; };
and MyClass() would call MyClass(5)
The purpose was just to show constructor chaining.
If i wanted to pass diffrent types i would just overload like
you pointed out. ;)