My question is simple. When do we need to have a default constructor? Please refer to the code below:
class Shape
{
int k;
public:
Shape(int n) : k
A default constructor will only be automatically generated by the compiler if no other constructors are defined. Regardless of any inheritance.
And also you need to construct your base class by calling:
Rect( int n ) : Shape( n ), l(n)
{
}
Compiler generates default constructor in case when you have not define any constructor. But if you have defined any constructor that takes some argument or not. The compiler will use that constructor and will not generate default constructor with zero argument.
See this for the full behaviors of C++ WRT constructors: http://en.wikipedia.org/wiki/Default_constructor
The simple answer is that if you specify a constructor, the compiler will not create a default one for you.
This rule applies to Java as well.
As you defined a Constructor for Shape expecting an integer you have overwritten the default constructor by doing so. So if you extend Shape you must pass an integer value to the superclass.
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.
The compiler will define a default ctor if and only if you don't explicitly declare any ctors.
Note that what's important is declaring the constructor, not necessarily defining it. It's fairly common, for example, to declare a private ctor, and never define it, to prevent the compiler from implicitly defining any others.
Edit: Also note that C++11 has an =default
syntax for dealing with situations like yours.