Re: Creating a class
saneman wrote:
In the main below I create a Swat class in three ways:
class Swat {
public:
Swat(){
n = 0;
}
Swat(int a){
n = a;
}
int getS() {
return n;
}
void setS(int b) {
n = b;
}
private:
int n;
};
int main() {
// First
Swat ss1;
ss1.setS(33);
// Second
Swat ss2();
That's a declaration of a function.
ss2().setS(22); // Illegal!
Illegal? Really? What's illegal about it? Did you make a typo and in
your code you actually *don't* have any parentheses after 'ss2'?
// Third
Swat* ss3 = new Swat();
ss3->setS(55);
printf("%d\n", ss1.getS());
printf("%d\n", ss3->getS());
return 0;
}
Only the First and Third class creation seems to make sense. My question
is:
1) When are // Second used?
When you want to declare a function.
2) When would // Third be necessary, seems that // First does the job just
fine.
When you want your object to outlive the scope.
3) Are there any other ways to create a class besides the 3 above?
3? Not 3, only 2. 'ss1' has automatic storage duration. 'ss2' is a
function (and not an object). 'ss3' has dynamic storage duration. If
you want static storage duration, you can either place the object's
declaration outside of any function or add the keyword 'static' to the
declaration.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask