Default constructor

A

al

class Base
{
public:
//Base() {}
Base(int m) {}

};

class Derive : public Base
{
public:
Derive(int m) {}

};


The above code keeps giving compiler error: 'Base': no appropriate default
constructor available, until a default cstor, Base() is added into Base
class.

Does this mean that a default cstor has always to be added whenever a
non-default cstor present?

Or is this default cstor, Base(), only required during inheritance? How to
make Derive to call Base(int m) rather than Base()?

In general, when does a default cstor have to be provided?

Thanks!
 
A

Adam Fineman

al said:
class Base
{
public:
//Base() {}
Base(int m) {}

};

class Derive : public Base
{
public:
Derive(int m) {}

};


The above code keeps giving compiler error: 'Base': no appropriate default
constructor available, until a default cstor, Base() is added into Base
class.

That's because your Derive contructor is attempting to construct a
default Base object, since you haven't told it how to initialize it's
Base component. Change your Derive contructor to this:

Derive(int m)
: Baee(m)
{
/* no code */
}

and it will compile without a default contructor for Base.
In general, when does a default cstor have to be provided?
Whenever an object must be initialized without any parameters.

- Adam
 
V

Victor Bazarov

al said:
class Base
{
public:
//Base() {}
Base(int m) {}

};

class Derive : public Base
{
public:
Derive(int m) {}

};


The above code keeps giving compiler error: 'Base': no appropriate default
constructor available, until a default cstor, Base() is added into Base
class.

Correct. In the 'Derive's constructor you don't initialise the Base in any
way. The compiler has to do it itself. It uses default-initialisation.
Since you have a parameterised c-tor in Base, and no default c-tor, the
compiler cannot initialise the Base part of Derive.
Does this mean that a default cstor has always to be added whenever a
non-default cstor present?
No.


Or is this default cstor, Base(), only required during inheritance? How to
make Derive to call Base(int m) rather than Base()?

class Derive : public Base
{
public:
Derive(int m) : Base(m) {}
};

BTW, what book are you using to learn C++ that doesn't tell you that?
In general, when does a default cstor have to be provided?

No.

Victor
 
D

Dan Cernat

In addition:

if you provide no constructor, the compiler will generate a 'default' (no
parameters) constructor. As soon as you declare a constructor (with or
without parameters), the compiler will no longer generate the default for
you.

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,883
Members
47,414
Latest member
djangoframe

Latest Threads

Top