When I have both the prototype and definition in the same header file (as shown below), and I create an object in main (source.cpp) with Cube c1{};
I get no error and the default constructor works; c1's side will be defaulted to 0.0
class Cube {
private:
double side;
static int counter;
//this is cube.h
public:
Cube(double s = 0.0) :side{ s } { //constructor
counter ;
}
};
However, when I separate the interface from the implementation like this:
class Cube {
private:
double side;
static int counter; //static data
//this is cube.h
public:
Cube(double);
};
Its implementation:
#include <iostream>
#include "Cube.h"
int Cube::counter{ 0 };
//this is cube.cpp
Cube::Cube(double s = 0.0) :side{ s } {
counter ;
}
And I go to the main function in source.cpp, Cube c1{};
now gives me the error:
no instance of constructor "Cube::Cube" matches the argument list
Note: When I gave c1 a value, like Cube c1{5};
it works in both cases.
CodePudding user response:
You should put the default argument to the declaration Cube(double = 0.0);
, not the definition. Otherwise the matching function cannot be found in other files.