+ 3
Objects inside Classes
I was wondering if I am allowed to create an object inside a class itself in C++ and if I was, what I would have to keep in mind if this object has a constructor? E.g. creating a base class object in a derived class.
3 Antworten
+ 13
In C++, a class cannot contain an instance of itself as a class member, because the class itself is not well-defined at that point, which will cause the compiler to throw errors, telling you that your class is of an incomplete type.
However, a derived class is able to have an instance of its base class as a class member, because the base class is already well-defined at the time of defining the derived class.
That said, there should be no reason for the derived class to need to have an instance of the base class.
+ 12
Imagine what you would be able to do if
class a
{
public: a obj;
};
can compile though. You would be able to do
a obj;
obj.obj.obj.obj.obj.obj.obj.obj..... all the way.
+ 3
Thanks for explaining it so well!
I already had an idea about it because I did some coding experiments, but I wanted to clarify it for myself.