If not, the following code is behaving like we can call non-static member functions without creating objects. Please clarify on this.
Main file:
#include <iostream>
#include "singleton.h"
int main() {
Singleton* ptr = Singleton::createInstance();
Singleton* ptr1 = Singleton::createInstance();
std::cout << "Object ptr: " << ptr;
ptr->showDetails();
return 0;
}
Singleton.h:
class Singleton {
Singleton();
public:
static Singleton* ptr;
~Singleton();
void showDetails();
static Singleton* createInstance();
};
Singleton.cpp
#include <iostream>
#include <cstddef>
#include "singleton.h"
Singleton* Singleton::ptr = nullptr;
Singleton::Singleton() {
std::cout << "Singleton constructor called." << std::endl;
}
Singleton::~Singleton() {
std::cout << "Singleton destructor called." << std::endl;
}
Singleton* Singleton::createInstance() {
std::cout << "Singleton createInstance called." << std::endl;
return ptr;
}
void Singleton::showDetails() {
std::cout << "This is the singleton class." << std::endl;
}
OUTPUT: ./app Singleton createInstance called. Singleton createInstance called. Object ptr: 0This is the singleton class.
Aucun commentaire:
Enregistrer un commentaire