0

I have written small program but getting undefined reference error. I'm not getting what I'm doing wrong

#include <iostream>

using namespace std;
class A()
{
private:

    static A *m_object;
    A()
    {
        m_object = NULL;
    }

public:

    static A* getSingleton();

    int returnVar()
    {
        return 45;
    }

};
A* A::getSingleton()
{
    if(A::m_object == NULL)
    {
       A::m_object = new A();
    }

   return m_object;
}
int main()
{
    cout<<"Hello World";
    A *a = A::getSingleton();
    cout<<"Address of a"<<&a<<endl;
    cout<<"return a"<<a->returnVar()<<endl;
    A *b = A::getSingleton();
    cout<<"Address of a"<<&b<<endl;
    return 0;
}

error

/home/main.o: In function `A::getSingleton()':
main.cpp:(.text+0x3): undefined reference to `A::m_object'
main.cpp:(.text+0x21): undefined reference to `A::m_object'
/home/main.o: In function `main':
main.cpp:(.text.startup+0x16): undefined reference to `A::m_object'
main.cpp:(.text.startup+0x7e): undefined reference to `A::m_object'
main.cpp:(.text.startup+0xcb): undefined reference to `A::m_object'
/home/main..o:main.cpp:(.text.startup+0xde): more undefined references to `A::m_object' follow
collect2: error: ld returned 1 exit status
Zoe
  • 27,060
  • 21
  • 118
  • 148
Happy
  • 3
  • 5

1 Answers1

0

When you declare a static variable inside a class it is only declared, but not defined. So you need to have an instance of the class inside a cpp.

#include <iostream>

using namespace std;
class A
{
private:

    static A *m_object;
    A()
    {
        m_object = NULL;
    }

public:

    static A* getSingleton();

    int returnVar()
    {
        return 45;
    }

};
A* A::getSingleton()
{
    if(A::m_object == NULL)
    {
       A::m_object = new A();
    }

   return m_object;
}

A* A::m_object; // You forgot this line

int main()
{
    cout<<"Hello World";
    A *a = A::getSingleton();
    cout<<"Address of a"<<&a<<endl;
    cout<<"return a"<<a->returnVar()<<endl;
    A *b = A::getSingleton();
    cout<<"Address of a"<<&b<<endl;
    return 0;
}
Victor Padureanu
  • 604
  • 1
  • 7
  • 12