2
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.

Community
  • 1
  • 1
Anuj
  • 1,160
  • 2
  • 20
  • 40

4 Answers4

8

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
5

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 (i.e. non-primitives) are always references.

Adam Batkin
  • 51,711
  • 9
  • 123
  • 115
2

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).

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

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.

Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63