Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ private static member variables

This C++ code is producing linker errors at compile time:

// A.h
class A {
    public:
        static void f();
    private:
        static std::vector<int> v;
};

// A.cpp
void A::f() {
    // this line is causing trouble
    int i = v.size();
}

Moving the vector declaration into the cpp file works. However I want to understand the linker error "Undefined symbols" cause in the above code. What is causing the linker error in the above code?

like image 215
SundayMonday Avatar asked May 25 '26 15:05

SundayMonday


2 Answers

Static members have to be defined in a compilation unit:

// A.cpp

vector<int> A::v;
like image 132
namezero Avatar answered May 28 '26 03:05

namezero


// A.h
class A {
    public:
        static void f();
    private:
        static std::vector<int> v;
};

// A.cpp
//modify add this line
static std::vector<int> A::v;
void A::f() {
    // this line is causing trouble
    int i = v.size();
}
like image 35
sunysen Avatar answered May 28 '26 05:05

sunysen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!