I'm trying to understand what's happening under the hood with the following piece of code. The question that I'm having trouble with is: How are static instances of classes handled in c++?
#include <iostream>
using namespace std;
class Shape {
public:
static Shape& getInstance() {
static Shape obj;
static Shape& objRef = obj;
return objRef;
}
void init() {
Shape singleton = Shape::getInstance();
srand((unsigned)time(0));
singleton.width = rand()%100;
singleton.printWidth();
}
void printWidth(){
cout<<width<<endl;
}
protected:
int width = 0;
};
int main()
{
Shape rectangle;
rectangle.init();
rectangle.printWidth();
return 0;
}
The output of this code is:
37
0
But to me, this doesn't make sense. If a static instance of Shape is made anywhere within the program, shouldn't there only be one Shape in memory? If any shapes call printWidth
after the singleton has set the width, shouldn't their width be equal to that width?
I would appreciate an explanation of where my thinking is going wrong.