Should We Always Include a Default Constructor in the Class

Should we always include a default constructor in the class?

You have to keep in mind that if you don't provide an overloaded constructor, the compiler will generate a default constructor for you. That means, if you just have

public class Foo
{
}

The compiler will generate this as:

public class Foo
{
public Foo() { }
}

However, as soon as you add the other constructor

public class Foo
{
public Foo(int x, int y)
{
// ...
}
}

The compiler will no longer automatically generate the default constructor for you. If the class was already being used in other code which relied on the presence of a default constructor, Foo f = new Foo();, that code would now break.

If you don't want someone to be able to initialize the class without providing data you should create a default constructor which is private to be explicit about the fact that you are preventing instances from being constructed with no input data.

There are times, however, when it is necessary to provide a default constructor (whether public or private). As was previously mentioned, some types of serialization require a default constructor. There are also times when a class has multiple parameterized constructors but also requires "lower level" initialization, in which case a private default constructor can be used which is chained in from the parameterized constructors.

public class Foo
{
private Foo()
{
// do some low level initialization here
}

public Foo(int x, int y)
: this()
{
// ...
}

public Foo(int x, int y, int z)
: this()
{
// ...
}
}

Do I really need to define default constructor in java?

A default (no-argument) constructor is automatically created only when you do not define any constructor yourself.

If you need two constructors, one with arguments and one without, you need to manually define both.

Should i define the default constructor?

This is likely to be closed as "primarily opinion-based," but I can give you some objective points to consider:

  • If you don't define the default constructor, and someone later adds a constructor with parameters and forgets to also add the parameterless constructor, the default constructor will go away and that could break existing code. Explicitly defining it ensures that even if someone adds an overloaded constructor later, the parameterless one is still there.

  • If the constructor is declared in the header and defined out-of-line (in a .cc/.cpp file), then the implementation can later be modified with dependent code only needing to be re-linked. Declaring a constructor after the fact necessarily affects the header, requiring recompilation of dependent code.

    • An empty out-of-line constructor will still need to be called, incurring a small run-time cost, whereas with an implicitly provided default constructor the compiler can see that nothing needs to be done and avoid the call.

  • Defining it explicitly requires more typing and results in more lines of code. There is a small but nonzero cost associated with this (time taken to type it in, and time taken for readers of the code to read through it).

  • Defining it explicitly disqualifies the class from being an aggregate class, unless you use =default in C++11.

Yes, these points are contradictory. I think you will find that the prevailing opinion is not to define it explicitly, but as far as the language is concerned there is no correct or incorrect way. (Unless you need your type to be an aggregate.)

When do we need to have a default constructor?

A default constructor is not synthesised if you created your own constructor with arguments. Since you gave Shape a constructor of your own, you'd have to explicitly write out a default Shape constructor now:

class Shape
{
int k;

public:
Shape() : k(0) {}
Shape(int n) : k(n) {}
~Shape() {}
};

(You can leave out the empty ~Rect() {} definitions, as these will be synthesised.)

However, it looks to me like you don't want a default constructor for Shape here. Have Rect construct the Shape base properly:

class Shape
{
int area; // I've had to guess at what this member means. What is "k"?!

public:
Shape(const int area)
: area(area)
{}
};

class Rect : public Shape
{
int l;
int w;

public:
Rect(const int l, const int w)
: Shape(l*w)
, l(l)
, w(w)
{}
};

Also note that this example is oft cited as an abuse of OO. Consider whether you really need inheritance here.

why constructor use, why not always use simple initialization of variables?

Simple definition of constructor:

Special methods that initialize an object of a class. Always and only used together with the new keyword to create an instance of a class.

  1. Has the same name as the name of the class.
  2. Can take one or more arguments.
  3. Has no return value, not even void.
  4. Default constructor takes no parameters.
  5. More than one constructor exist (method overloading).

but why use constructor initialization if it automatically done by
compiler !

Constructors initialize by the compiler (default constructor) if you have not implemented a constructor.

So why do we need to implement a constructor?

  • Its job is to tell all of the local variables their initial values,
    and possibly to start off another method within the class to do
    something more towards the purpose of the class.
  • Depends on what data you have, i.e. what is available.
  • Different ways of creating an object.
  • All class variables have to be initialized with the constructor.

As a example:

  • Consider the Rectangle class in the java.awt package which provides several different constructors, all named Rectangle(), but each with a different number of arguments, or different types of arguments from which the new Rectangle object will get its initial state. Here are the constructor signatures from the java.awt.Rectangle class:

  • public Rectangle()

  • public Rectangle(int width, int height)
  • public Rectangle(int x, int y, int width, int height)
  • public Rectangle(Dimension size)
  • public Rectangle(Point location)
  • public Rectangle(Point location, Dimension size)
  • public Rectangle(Rectangle r)

What if your member variables are private (security reasons)? If you do not want to give other classes to handle member variables, you have to use getters and setters, but in the first place, you can initialize it with a constructor, then you can change it using getters and setters later on when you need to change/update it.



Related Topics



Leave a reply



Submit