Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non static members as default parameters in C++

I'm refactoring a large amount of code where I have to add an extra parameter to a number of functions, which will always have a value of a member of that object. Something like

class MyClass
{
public:
   CMyObject A,B;

   void MyFunc(CMyObject &Object);
   // used to be void MyFunc();
};

Now, I'd actually like it to read

class MyClass
{
public:
   CMyObject A,B;

   void MyFunc(CMyObject &Object = A);
};

But I'm not allowed to have a default parameter that is a non-static member. I've read this similar question which suggest this isn't possible, but I'm wondering if there is any reasonable workaround. Reason being that 95% of the time the default parameter will be used, and thus using a default parameter would hugely reduce the amount of code I have to change. My best solution so far is something like this;

class MyClass
{
public:
   CMyObject A,B;

   void MyFunc(BOOL IsA = TRUE);
};

void MyClass::MyFunc(BOOL IsA)
{
    CMyObject &Object = A;
    if (!IsA)
        Object = &B;
}

This is less than elgant, but is there a better way of doing this that I'm missing?

Edit: FWIW, the reason for the extra parameter is to externalize some state related members from the object in question to aid multi-threading.

like image 738
SmacL Avatar asked Feb 19 '10 12:02

SmacL


People also ask

Does C allow default parameters?

There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.

Where can a non-static reference member variable of a class be initialized?

Member initialization Non-static data members may be initialized in one of two ways: 1) In the member initializer list of the constructor.

What are the parameters that are default?

Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

What is a non-static member object?

A non-static member function is a function that is declared in a member specification of a class without a static or friend specifier. ( see static member functions and friend declaration for the effect of those keywords)


1 Answers

How about :

class MyClass
{
public:
   CMyObject A,B;

   void MyFunc()
   { 
     MyFunc(A); 
   }
   void MyFunc(CMyObject &Object);
};

?

like image 53
Benoît Avatar answered Oct 02 '22 14:10

Benoît