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 ?
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:
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
Containercontains anotherContainerwhich contains anotherContainerand so on…