简体   繁体   中英

why can't we declare object of a class inside the same class in C++ but it is allowed in Java?

class A
{
    A a;//why can't we do this in C++ but it is allowed in Java?
};

Using this question , i came to know why it is not allowed in C++ but why is it allowed in java? According to same argument of not knowing the memory size while compilation, it should not be allowed in Java as well.

In Java, if you have A a; , a is a reference to an object of class A . In C++, it's not a reference, it's a complete object.

So the resulting object in C++ would be of infinite size, which isn't very practical.

In C++, you CAN do this:

class A {
    A *a;
}

This is how you would implement many data structures, including linked lists.

As you mentioned, you CAN'T do this in C++:

class A {
    A a;
}

You can't do that in C++ for a couple reasons: Not only because it doesn't know the memory size of A (as you mentioned), but also because it would mean that every A would have a member of type A which would recurse on forever.

So, Java, allows the equivalent of the first example above:

class A {
    A a;
}

It just so happens that this syntax looks the same as the second example of C++ syntax, but in fact, it has the same meaning as the first C++ example: Class A has a member variable of type "pointer" (C++) or "reference" (Java) to an object of class A .

The second C++ syntax has no equivalent Java syntax, because in Java, all instances of a class (ie non-primitives) are always references.

In Java, this

 A a;

means A is a reference to an A object. So class A does not contain an A instance, like it would in C++ (which would be infinitely recursive, hence not allowed).

A a; creates a reference in Java but not in C++ .

Having an instance of the same object inside one object will not be possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM