Home > Back-end >  One Definition Rule and static member initialization
One Definition Rule and static member initialization

Time:05-02

I've read the one definition rule yet could not find the answer to what I'm trying to achieve.

I'm implementing a class in which I need to count every occurrence created of this class, let's name it "Item"

Such that when the header and CPP files are complicated, the static member is defined and with every call to the class' constructor, said static member grows by one and applied to current object that is created. (That is how I presume things are happening 'back stage')

Thanks for any help!

CodePudding user response:

I was using Item::idCounter all along, while I needed to use int Item::idCounter;

Weirdly, no flags were raised about this.

CodePudding user response:

What you want to do is essentially a Singleton model. here are 3 files working example: test.h

class myClass{
    protected:
        static myClass *hinst;
        int inst_count;
        myClass();
        ~myClass();
    public:
        static myClass * getInstance();
        int count() const;
};

test.cpp

#include "test.h"

myClass::myClass(){
    this->inst_count=0;
}

myClass *myClass::hinst = 0;

myClass * myClass::getInstance(){
    if(hinst==0)
        hinst = new myClass();
            
    myClass::hinst->inst_count  ;
    return myClass::hinst;  
}

int myClass::count() const{
    return this->inst_count;            
}

test_main.cpp

#include <stdio.h>
#include "test.h"

int main(){
    myClass *pp= myClass::getInstance();

    printf("%ld\n", pp->count());
    printf("%ld\n", myClass::getInstance());
    printf("%ld\n", myClass::getInstance());
    printf("%ld\n", myClass::getInstance());
    printf("%ld\n", myClass::getInstance());
    printf("%ld\n", pp->count());
    return 0;
}

Compile, Run and output

> c    test_main.cpp test.cpp -o test_main.exe && test_main
1
3878864
3878864
3878864
3878864
5
  • Related