Below code instantiates a derived singleton object based on environment variable. The compiler errors saying error C2512: 'Dotted' : no appropriate default constructor
. I don't understand what the compiler is complaining about.
EDIT: Fixed issues with implementing the get instance method which requires definition of both the parent and derived class. By separating the class definitions in separate header files and including the same in Singleton.cpp where the instance function is implemented.
Mainfile – 1
#include <iostream>
#include <string>
#include "Singleton.h"
using namespace std;
int main(){
Singleton::instant().print();
cin.get();
}
Singleton.h
#pragma once
#include <iostream>
using std::cout;
class Singleton{
public:
static Singleton & instant();
virtual void print(){cout<<"Singleton";}
protected:
Singleton(){};
private:
static Singleton * instance_;
Singleton(const Singleton & );
void operator=(const Singleton & );
};
Singleton.cpp
#include "Singleton.h"
#include "Dotted.h"
Singleton * Singleton::instance_ = 0;
Singleton & Singleton::instant(){
if (!instance_)
{
char * style = getenv("STYLE");
if (style){
if (strcmp(style,"dotted")==0)
{
instance_ = new Dotted();
return *instance_;
} else{
instance_ = new Singleton();
return *instance_;
}
}
else{
instance_ = new Singleton();
return *instance_;
}
}
return *instance_;
}
Dotted.h
#pragma once
class Dotted;
class Dotted:public Singleton{
public:
friend class Singleton;
void print(){cout<<"Dotted";}
private:
Dotted(){};
};