Search code examples
c++templatesdeclarationmember

how to create a templated class that has a member of that same class?, initialized it's value at some point?, and avoid pointers if possible


let us say I have a templated class and inside that class I want to have an uninitialized member of that same class, and possibly at some point I want to initialize that member of that class, how am I gonna do this in C++?, and as much a possible I also wanted to avoid pointer based solutions because of possible memory leaks, but if not then I would still accept pointer base solutions, I have the code below:

#include <iostream>

template<typename T>
class self
{
    private:     
        int id;

    public:
        self() : id(-1) {}
        self(int id) : id(id) {}

        self inner_self;

        void init_inner_self(int id)
        {
            inner_self = self(id);
        }

        void show_self()
        {
            std::cout<<id<<'\n';
        }
};

int main()
{
    self<int> a(5);
    a.show_self();
    
    a.init_inner_self(3);
    a.inner_self.show_self();

    return 0;
}

As you can see I have a template class called template<typename T> class self in there I have a member called inner_self which is of the same type of the class self and is not initialized yet when instantiating a self object, and I want to use the function void init_inner_self(int id); to initialize that member later on.

For this code I'm expecting it to output the ff.

5
3

but I cannot even compile it, the compiler says

sample5.cpp: In instantiation of ‘class self<int>’:
sample5.cpp:28:16:   required from here
sample5.cpp:13:14: error: ‘self<T>::inner_self’ has incomplete type
   13 |         self inner_self;

I have also tried to make the member declaration into self<T> inner_self; but still there is no success, can someone help? Is this behavior even possible or allowed in C++?


Solution

  • If a class contains itself as a member, then that member contains the same class as a member which contains the same class as a member which contains the same class as a member which contains the same class as a member which contains the same class as a member ... can you spot the problem?

    It is simply impossible for a class to contain a non-static member of its own type. And of course, a class isn't complete within its own definition, and a non-static member must have a complete type.

    Whether the class is instance of a class template or not has no effect on this.