I wan to have my class in a separate .h file, and the implementation in a .cpp file. The problem I run into is "Multiple definition of methodname". If I put the content of both files in a .hpp file it works, but I'm not sure if I should use that.
The .h File:
#pragma once
class Nincs;
class Sugar
{
public:
Sugar(){}
};
class Nincs : public Sugar
{
private:
static Nincs* ins;
Nincs(): Sugar() {};
public:
static Nincs* instance();
};
the .cpp File:
#include "Sugar.h"
Nincs* Nincs::ins = nullptr;
Nincs* Nincs::instance() //the error is with this line
{
if (ins == nullptr)
{
ins = new Nincs();
}
return ins;
};
The main .cpp file:
#include <iostream>
#include "Sugar.cpp"
using namespace std;
int main()
{
Nincs* n = Nincs::instance();
return 0;
}
Basically, I am struggling with making a simple singleton class in C .
CodePudding user response:
The problem is that you're including the source file(Sugar.cpp) instead of the header file(Sugar.h).
To solve this inside main.cpp
, change #include "Sugar.cpp"
to:
#include "Sugar.h"
Also it is recommended that we should never include source files.