user2935354
user2935354

Reputation:

Error "collect2: ld returned 1 exit status" while compiling

When I am building following source code:

#include <stdio.h>

class Heap
{
    public:
        Heap()
        {
            printf("Heap()");
        }
        void* print()
        {
            printf("This is Heap Print");
        }
};

class DvHeap : public Heap
{
    public:
        DvHeap():Heap()
        {
            printf("DvHeap()\n");
        };
};

template<class T>
class base
{
    public:
        void* operator new(size_t size)
        {
            printf("base()\n");
            return T::printit().print();
        }
};

template<class T>
class derived : public base<derived<T> >
{
    static  DvHeap xx;
    public:
        static Heap& printit()
        {
            printf("DvHeap()\n");
           return xx;
        }
}; 

int main()
{
    //DvHeap *pH = new DvHeap(1);
    derived<DvHeap> *pD = new derived<DvHeap>;
    return 0;
}

I am getting following error:

[debdghos]$ g++ Ctest.cpp -o test

/tmp/ccM7XI3u.o: In function derived<DvHeap>::printit()': Ctest.cpp:(.text._ZN7derivedI6DvHeapE7printitEv[derived<DvHeap>::printit()]+0xf): undefined reference toderived::xx' collect2: ld returned 1 exit status

Can any one tell me why this happening? The code is for learning purpose.

Thanks

Upvotes: 0

Views: 982

Answers (2)

iDebD_gh
iDebD_gh

Reputation: 374

Complete code:

include <stdio.h>

class Heap
{
    public:
        Heap()
        {
            printf("Heap()");
        }
        void* print()
        {
            printf("This is Heap Print");
        }
};

class DvHeap : public Heap
{
    public:
        DvHeap():Heap()
        {
            printf("DvHeap()\n");
        };
};

template<class T>
class base
{
    public:
        void* operator new(size_t size)
        {
            printf("base()\n");
            return T::printit().print();
        }
};

template<class T>
class derived : public base<derived<T> >
{
    static  DvHeap xx;
    public:
        static Heap& printit()
        {
            printf("DvHeap()\n");
           return xx;
        }
}; 
    template<typename T>
    DvHeap derived<T>::xx;
int main()
{
    //DvHeap *pH = new DvHeap(1);
    derived<DvHeap> *pD = new derived<DvHeap>;
    return 0;
}

Read this where you was wrong: http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

Upvotes: 0

ForEveR
ForEveR

Reputation: 55897

You should initialize static member outside of the class.

template<typename T>
DvHeap derived<T>::xx;

Upvotes: 1

Related Questions