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.

0

4 Answers 4

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.

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

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

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.