C++ Examples
- Write a C++ Program to print a welcome text in a separate line.
Singleton C++ example
#include <iostream>
using namespace std;
class a1 {
static a1 *i;
// Variable declaration
int x;
// Private constructor
a1() {
x = 5;
}
public:
static a1 *getInstance() {
if (!i)
i = new a1;
return i;
}
int getData() {
return this -> x;
}
void setData(int x) {
this -> x = x;
}
};
//Initialize pointer to NULL
a1 *a1::i = NULL;
int main(){
a1 *obj1 = obj1->getInstance();
cout << obj1->getData() << endl;
obj1->setData(400);
cout << obj1->getData() << endl;
return 0;
}
Output
5
400