But my IDE (Qt Creator) gives a warning that "unexpected token (" and for some of the others says "extra ;".
Is that syntax correct and these warnings are just bugs or else ?
It's not possible for a class to contain a member whose type is the same class. An object must be is at least as big as the sum of the sizes of all its members. If one of its members is an instance of the same class, what is the size of the object?
sizeof(MyClass) = sizeof(MyClass) + sizeof(MyClass)
x = x + x
x = 2 * x
x / x = 2
1 = 2
Obviously, unconditionally calling MyClass::MyClass(std::string) from MyClass::MyClass(std::string) causes infinite recursion. Don't do that.
std::unique_ptr is defined by including the <memory> standard header. If you're using an older compiler, you can use naked pointers, but you'll have to manage the memory manually.
It's only a fine point and doesn't detract from your explanation to OP.
Take x = x + x as true then subtracting x from both side gives x = 0 and that's why the division later on leads to the nonsense (we both agree) of 1 = 2.
To my mind the doubling of the size (x = 2*x) was a compelling reason while the 1=2 conclusion might be equally compelling to others but not me. Take your pick I suppose. :)
> I have a class and i want to define some variables on it which the data types are the same with that class name.
After MyClass is declared, but before its definition is completed, the type MyClass is an incomplete type.
We can't define an object or declare a (non-static) member object with an incomplete type.
A class that has been declared but not defined, an enumeration type in certain contexts, or an array of unknown size or of incomplete element type, is an incompletely-defined object type. Incompletely-defined object types and the void types are incomplete types. Objects shall not be defined to have an incomplete type.
Footnote: The size and layout of an instance of an incompletely-defined object type is unknown.
- IS
and
Non-static data members shall not have incomplete types. In particular, a class C shall not contain a non-static member of class C, but it can contain a pointer or reference to an object of class C.
- IS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
struct A ; // A is an incomplete type at this point
A a ; // *** error: A is an incomplete type
void v ; // *** error: void is an incomplete type
struct B
{
int i ;
// B is an incomplete type at this point
struct C
{
A a ; // *** error: A is an incomplete type
B b ; // *** error: B is an incomplete type
};
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
struct A ; // A is an incomplete type at this point
struct B
{
int i ;
struct C ;
}; // type B is a complete type at this point
struct A { double d ; }; // A is a complete type at this point
A a ; // fine, complete type
struct B::C
{
A a ; // fine, complete type
B b ; // fine, complete type
};