0

I have the following class definition and the main(). Can someone please point me why I am getting the error?

#include <iostream>
#include <list>
using namespace std;

class test
{
protected:
  static list<int> a;
public:
  test()
  {
    a.push_back(150);
  }
  static void send(int c)
  {
    if (c==1)
      cout<<a.front()<<endl;
  }
};

int main()
{
  test c;
  test::send(1);
  return 0;
}

The error that I get is as follows:

/tmp/ccre4um4.o: In function `test::test()':
test_static.cpp:(.text._ZN4testC1Ev[test::test()]+0x1b): undefined reference to `test::a'
/tmp/ccre4um4.o: In function `test::send(int)':
test_static.cpp:(.text._ZN4test4sendEi[test::send(int)]+0x12): undefined reference to `test::a'
collect2: ld returned 1 exit status

The error is same even if I use c.send(1) instead of test::send(1). Thanks in advance for the help.

2 Answers 2

6

You've declared test::a, but you haven't defined it. Add the definition in namespace scope:

list<int> test::a;
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry. I did not understand. Can you please elaborate?
@Neel : What would you expect to happen if you declared a function void foo(); but called it without defining it? Clearly such a thing cannot work. The same goes for static data members -- declaring them is not sufficient, they must also be defined. My answer shows the syntax for that definition.
Thank you. I got it. Even after so many years of working with C++, I never recollect having done anything like this for static variables. Thanks for the help.
1

a is declared but must still be defined. http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.