Mail Archives: djgpp/1997/05/22/12:06:34
>> >in C++ is possible to have default arguments to member functions
>> >(i.e. int foo( int bar = 3 ) {...} ) .
>> >Could I have, as default value, the value of a member variable ?
>> >(i.e. something like:
>> >
>> >struct Question {
>> > int zoo;
>> > Question() : zoo(3) {} // this makes evrybody happy ;)
>> > int foo( int bar = Question::zoo );
>> >}
>> >
>>
>> Question: Why not just make
>>
>> int foo(int bar=3);
>>
>> the default? It does the exact same thing as this snipet of code you've
>> shown us. Am I missing something here? Your method might work if
>> you make zoo static, but I'm still not even sure of it or it's need.
>
>I want zoo to be a variable. In this example I assigned 3 to zoo
>to avoid a : "Ehi, you are handling uninit. vars" answer.
>
>And if I declare it static:
>s.cc:5: field `int Question::zoo' is static; only point of
>initialization is its declaration
>where line 5 is Question() : zoo(3) {}
Ok, I think I understand. You want Zoo to point to some default value
that can change. I think you probably want this, keep in mind two
things,
first you can only declare default values for static variables outside
of the
class (at least I think that is true) and I changed this from a struct
to a
class. I compiled this, and it compiles fine. g++ can't find the g++
library
for some reason, so I couldn't run it, but it should work.
Also, since zoo is static, it is common to all classes. If you don't
want
that, I think you are out of luck. g++ won't compile that saying zoo
must
be static. I suspect this is because if zoo was variable, the function
would
never know which value to look at in which class. I don't see why this
is
a problem, but then again the C++ standards comittee hasn't really
accomplished much the last few years, so who knows why.
#include "iostream.h"
class MyClass
{
private:
static int zoo;
public:
MyClass()
{
cout << "Wee! I do nothing!!" << endl;
}
SetDefaultValue(int x)
{
zoo = x;
};
int Foo(int val = MyClass::zoo)
{
cout << val << endl;
};
};
int MyClass::zoo = 3;
int main()
{
MyClass temp;
temp.Foo();
temp.SetDefaultValue(5);
temp.Foo();
temp.Foo(3);
};
- Raw text -