ConstructorReturnsObject

Misconception:

A constructor needs to return an object, and it needs a return type corresponding to its class.

Incorrect

Constructors need to return objects

Correct

Constructors cannot return anything

Correction
Here is what's right.

A constructor does not return any value. It does not create anything, it just initializes the given object (the object pointed to by this).

Origin
Where could this misconception come from?

This misconception may come from how constructors are used:

Object o = new Object();

In the above code, the expression new Object() produces a value. Students may believe that for it to produce a value, the constructor has to produce that value. They may believe that this expression is only a constructor call. However, the object is not produced by the constructor, but by the new Object() expression, which allocates the object, calls the constructor to initialize it, and then produces the initialized object.

Symptoms
How do you know your students might have this misconception?

Do your students write:

  • Constructors that return this
  • Constructors (of a class C) that return new C()
  • Constructors with a return type in their header

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.