I've created two classes - a base class and derived class where the base class is a singleton.
When I call the derived class constructor, which object is being created as the static instance? Is it a base class object or derived one, and why?
As
#include <iostream>
class Singleton {
protected:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance= nullptr;;
class DerivedSingleton : public Singleton {
public:
int x;
static DerivedSingleton* getInstance() {
if (!instance) {
instance = new DerivedSingleton();
}
return (DerivedSingleton*)instance;
}
};
int main(){
Singleton *instance = DerivedSingleton::getInstance();
std::cout << sizeof(DerivedSingleton) << std::endl;
std::cout << sizeof(*instance) << std::endl;
std::cout << sizeof(Singleton) << std::endl;
}
Output :
4
1
1
I tried printing the values of the sizes but i cant connect why the base class object is being created.
Only one object is created, which is of type DerivedSingleton. This is because DerivedSingleton::getInstance() is called, and it ensures that only one instance of DerivedSingleton exists throughout the program.