The compiler is complaining about my default parameters? – C++

Photo of author
Written By M Ibrahim
abstractclass c++11 optional-parameters

The Problem:

I’m trying to use default parameters in a void function of a class, but the compiler is giving me an error. I split the class into a .h and .cpp file and the error started appearing.

The Solutions:

Solution 1: Specify default parameter values only in declaration

In the class declaration (header file), specify the default value for the _color parameter of the setColor method, like this:

// pbase.h
class pBase : public sf::Thread {
    // ...
    void setColor(int _color = -1);
    // ...
};

In the method definition (source file), do not specify the default value again:

// pbase.cpp
void pBase::setColor(int _color) {
    // ...
}

By specifying the default value only in the declaration, you avoid the error "redefinition of default parameter".

Solution 2: resolve the error

The error is caused by the redefinition of the default parameter in the header file. To fix this, add

`#pragma once`

to the top of the header file. This will prevent the header file from being included multiple times, which will in turn resolve the error.

Solution 3: Remove Redundant Header Files

In the provided scenario, the error was caused by having the same header file (pBase.h) included in multiple paths. This can lead to redefinition of default parameters like the one seen in the error message.

To resolve this issue, ensure that the header file is only included once in the project. This can be done by checking the include paths and removing any redundant instances of the header file.