0

I am trying to define an object of mylist inside the mylist class.

here is my code:

mlist.h

#ifndef MLIST_H
#define MLIST_H

#endif // MLIST_H

#include "mylist.h"

template <class T> class mlist
{
protected:
    T item = 0;
    mylist<T> next = 0;
};

mylist.h

#ifndef MYLIST_H
#define MYLIST_H

#include "mlist.h"

template <class T> class mylist : mlist<T>
{
private:
    T item;
    mylist<T>* next;

// --- some functions ---

};

#endif // MYLIST_H

the error:

error: 'mylist' does not name a type

mylist next = 0;

my question: What is going wrong and what is the correct way on doing this?

Community
  • 1
  • 1
Dylan Westra
  • 611
  • 1
  • 5
  • 10

2 Answers2

1

You can't define a concrete object of a class inside its definition because at the time the compiler sees the objects definition it knows nothing about its class.

You can however define a pointer to an object of the same class inside the class's definition.

Also your code suffers from the problem of circular dependency.

Now, in order to solve this you have to forward declare template class mylist before the definition of template class mlist. If you do this however, you introduce another problem, that is you can't have a concrete object of class mylist inside the definition of class mlist. Again this is solved by defining a pointer to an object of class mylist inside the definition of class mlist:

template<class T> class mylist;

template <class T>
class mlist {
protected:
  T item;
  mylist<T>* next;
};

template <class T>
class mylist : mlist<T> {
  T item;
  mylist<T>* next;
};

int main() {
  mylist<int> lst;
  (void) lst;
}

LIVE DEMO

101010
  • 41,839
  • 11
  • 94
  • 168
0

I am trying to define an object of mylist inside the mylist class.

Actually this is not everything you try to do. You try to have a my list member both in mylist and mlist. I think you try to use something which does not exist in C++ - pure virtual members. The lines

protected:
 T item = 0;
 mylist<T> next = 0;

Look like you intended it. The also cause mutual dependency between mlist and mylist because you try to have mylist member in mlist, and you try to derive mylist from mlist.

Remove the lines I quoted above and your compilation error should be gone.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51