|
-
Jun 25th, 2001, 11:40 AM
#1
Thread Starter
Fanatic Member
Constructors?
How do you have and use more than one constructor for a class?
Alcohol & calculus don't mix.
Never drink & derive.
-
Jun 25th, 2001, 12:04 PM
#2
Monday Morning Lunatic
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
}
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Jun 25th, 2001, 12:35 PM
#3
Thread Starter
Fanatic Member
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
}
Alcohol & calculus don't mix.
Never drink & derive.
-
Jun 25th, 2001, 07:12 PM
#4
Dazed Member
"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.
-
Jun 26th, 2001, 12:04 AM
#5
transcendental analytic
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)
Use  
writing software in C++ is like driving rivets into steel beam with a toothpick.
writing haskell makes your life easier:
reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.
-
Jun 27th, 2001, 07:08 PM
#6
Dazed Member
The purpose was just to show constructor chaining.
If i wanted to pass diffrent types i would just overload like
you pointed out.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|