Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Class Variables as Default Parameters

Status
Not open for further replies.

MukeshMak

Technical User
Aug 6, 2002
19
CH
Hi all,

I'm trying to use class variables as default parameters in my C++ code but get the following error:

var_A : use of member as default parameter requires static member

To illustrate my problem here is an example class:

class exampleClass {
private:
int var_A;

public:

int exampleMethod ( int varMethod = var_A )
{
.
.
.
}
};

Can I still do this and avoid declaring the var_A variable as 'static'.

Thanks in advance for all the replies.
 
I think not. The compiler needs an address to supply the default value at compile time. The addres of a non-static member variable cannot be determined at compile time.
Greetings,
Rick
 
I dont understand why you need to do this. If the class knows what the variable is when the function is called, why tell the member function what it already knows? The only reason I can think of is at some time you may want to kill 2 birds with one stone and rather then call "SetVarA(value)" you would prefer to do a check in the member function and set it if it is different. The only way to accomplish this, in my opinion, is not to pass the member variable but have a class specific value that Var_A can never be. For situations like this I do things like

#define INVALID_VALUE ~0 // dont forget the tilde

then the member fucntion would be

int exampleMethod ( int varMethod = INVALID_VALUE)
{
if(varMethod != INVALID_VALUE)
var_a = varMethod;

// on with the code

}

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top