Frank Q.
Frank Q.

Reputation: 6592

Class having a member of same class type

I have the following code in C++ which does not compile:

class Container;
class Container
{
    std::string m_Name;
    Container m_Container;
};

This is because I have a member with the same type and the compiler cannot infer the size of the object here.

What makes this work using C# ?

namespace Sample
{
    public class Container
    {
        public string m_Name;
        public Container m_Container;
    }
}

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            Container con = new Container();

        }
    }
}

This compiles fine in C#. How is the size of the object been calculated here ?

Upvotes: 0

Views: 244

Answers (1)

K-ballo
K-ballo

Reputation: 81349

The fact that it works in C# is that all objects are handled as pointers. That is, your C# code would be equivalent to this C++ code:

class Container;
class Container
{
    std::string* m_Name;
    Container* m_Container;
};

The size of a pointer is known, and hence everything compiles. There is no need to know the size of the object at all. However, you don't want to go throwing pointers around in C++, specially raw pointers.

Note that in your original implementation, the size of the object not only is unknown but its also infinite since each Container contains another Container which contains another Container and so on...

Upvotes: 8

Related Questions