Search code examples
c++staticvirtual

can we access static member variable of pure virtual class?


Please consider the following code:

#include<iostream>

/* pure virtual class*/
class cTest {
    public:
        cTest(void);
        static void sFuncG(void);
        static void sFuncS(int);
        virtual void vFunc(void) = 0;
    private:
        static int  sVar;
};
/*the constructor dose nothing meaningful*/
cTest::cTest(void)
{
    return;
}

/*there are two static function who needs to access the static member variable*/
void cTest::sFuncS(int num)
{
    sVar = num;
}

void cTest::sFuncG(void)
{
    std::cout<<sVar<<std::endl;
}
/*the derived class*/
class cDrvd : public cTest {
    public:
        cDrvd(int);
        virtual void vFunc(void);
    private:
        int mem;
};

cDrvd::cDrvd(int num)
{
    mem = num;
}

void cDrvd::vFunc(void)
{
    cTest::sFuncS(mem);
}

int main()
{
    cDrvd myClass(5);
    cTest::sFuncG();
    return 0;

}

When I try to build the code, I am getting linker error:

me@My-PC:MyTestProgs$ g++ -o testStatic testStatic.cpp 
/tmp/ccgUzIGI.o: In function `cTest::sFuncS(int)':
testStatic.cpp:(.text+0x22): undefined reference to `cTest::sVar'
/tmp/ccgUzIGI.o: In function `cTest::sFuncG()':
testStatic.cpp:(.text+0x2e): undefined reference to `cTest::sVar'
collect2: error: ld returned 1 exit status

I found the problem in a large code and tried to reproduce it in the above code of mine.

What I understood is:

  • static member variables are created when the 1st instance of the class is created.
  • Here, no instance of class cTest is created, so the static member variable sVar is not present.
  • As the class cTest is pure virtual, we can not create an instance of it. So we cannot access sVar.

I am fairly new to c++, keeping in that mind, Will anyone please confirm my understanding?

If that is the case, what is the workaround for the situation?


Solution

  • You have to define static member

        static int  sVar;
    

    independently of the class in implementation file.

    int cTest::sVar = 0;  //initialization is optional if it's 0.
    

    As far as your questions concerned :-

    Q1) static member variables are created when the 1st instance of the class is created.
    

    No static member is there even when no instance of class is created.

    Q2) Here, no instance of class cTest is created, so the static member variable sVar 
    is not present.
    

    Static member variable would be there as explained above.

    Q3)As the class cTest is pure virtual, we can not create an instance of it. 
    So we cannot access sVar.
    

    You can access sVar like cTest::sVar.