Search code examples
c++constructordefault-parameters

Default Argument in non-inline Constructor


I've written a Cell class. When I write constructor with default parameters as inline function, there is no problem

cell.h
    Class Cell{
    public:
        Cell(int x, int y, char sign='.'):X(x), Y(y), Sign(sign){}  
    };

But if I want to move that implementation in my source file like this:

cell.h
        Class Cell{
        public:
            Cell(int x, int y, char sign='.');
        };
cell.cpp
    Cell::Cell(int x, int y, char sign='.'):X(x), Y(y), Sign(sign){}    

Compiler says:

Reversi.cpp:1144:43: error: default argument given for parameter 3 of ‘Cell::Cell(int, int, char)’ [-fpermissive]
     Cell::Cell(int x, int y, char sign='.'):X(x), Y(y), Sign(sign){}    
                                           ^
In file included from Reversi.cpp:7:0:
Reversi.h:16:5: note: previous specification in ‘Cell::Cell(int, int, char)’ here
     Cell(int x, int y, char sign='.');    
     ^

Solution

  • You're trying to specify the default parameters in both files. Only do it within the Header File, and the compiler will stop complaining.

    cell.h

    Class Cell
    {
        public:
        Cell(int x, int y, char sign);
    };
    

    cell.cpp

    Cell::Cell(int x, int y, char sign='.'):X(x), Y(y), Sign(sign)
    {
    }