0

I am trying to make a member variable in a class available as lifetime storage with the object (translation unit), so I made it static:

#include <iostream>

class A {
    public:
    std::string firstName;
    static std::string lastName;
    
    void assignFirstName() {
        std::cout << "Enter First Name: ";
        getline (std::cin, firstName);
    }
};

int main()
{
    A objA;
    objA.assignFirstName();
    objA.lastName = "Anderson";
    
    std::cout << objA.firstName << " " << objA.lastName << '\n';
    
    return 0;
}

but then I got error:

undefined reference to `A::lastName[abi:cxx11]'

I don't quite understand why I am getting this error. I searched online and saw one post talking about adding inline and therefore I gave it a try, surprisingly it worked but with a warning.

inline static std::string lastName;

The warning:

warning: inline variables are only available with -std=c++1z or -std=gnu++1z
     inline static std::string lastName;

I am not quite sure what's going on with the concepts behind all these. Could anyone demystify these? or any recommended explanations about these?

Thank you.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Jason T.
  • 113
  • 1
  • 2
  • 7
  • 1
    need to define your static variable outside class std::string A::lastName = ""; – Asphodel Jan 31 '22 at 19:42
  • 2
    A `static` member variable exists once and only once for every instance of the class. Traditionally you had to define it outside the class once and only once in your program to get storage allocated correctly, but this has softened in more recent revisions of the C++ Standard (this `-std=c++1z` stuff) and `inline` `static` members was added in C++'s 2017 revision. Since your compiler refers to C++17 as C++1z, it's a bit out of date, but adding `-std=c++1z` to the compiler command line should work. – user4581301 Jan 31 '22 at 19:46
  • 1
    `inline` will work without warning if you are using C++17 or later. Inline variables were added to C++17. You must be compiling an earlier standard. – Drew Dormann Jan 31 '22 at 19:56
  • Thanks for helps! I finally got it. As @Asphodel mentioned, I either will need to add another one line "std::string A::lastName;" outside the class for using ```static``` member inside the class definition or I will just need to update my compiler to C++17 to use ```inline static``` member inside the class definition. – Jason T. Jan 31 '22 at 20:02
  • 1
    @Jason - Note that C++17 is *also* "old", as the current standard is C++20. :-) – BoP Jan 31 '22 at 20:30
  • 2
    I consider C++17 to be mainstream. C++20 was a huge leap forward in a lot of ways and the weirds are still being worked out of the compilers for the trickier bits. – user4581301 Jan 31 '22 at 20:54

0 Answers0