no appropriate default constructor available

D

denis_browne

When writing the following code:

class Base
{
Base(const Base &rhs) {}
~Base();
};

void f() {
Base b;
};

The compiler shouts: no appropriate default constructor available

But when changing it to:

void f() {
Base b();
};

it compiles. Why?
 
J

John Carson

When writing the following code:

class Base
{
Base(const Base &rhs) {}
~Base();
};

void f() {
Base b;
};

The compiler shouts: no appropriate default constructor available

But when changing it to:

void f() {
Base b();
};

it compiles. Why?

Because in the second case you haven't declared an instance of Base. You
have instead declared a function that takes no arguments and returns a Base
object.
 
J

Jakob Bieling

When writing the following code:

class Base
{
Base(const Base &rhs) {}
~Base();
};

void f() {
Base b;
};

The compiler shouts: no appropriate default constructor available

But when changing it to:

void f() {
Base b();
};

it compiles. Why?

Base b(); declares a function 'b' taking no arguments and returning
an object of type 'Base'. Not so many days ago I read a nice 'rule of
thumb', if you may call it that: If it looks like a function
declaration, it is a function declaration. (Or something along the
lines)

hth
 
N

n2xssvv g02gfr12930

When writing the following code:

class Base
{
Base(const Base &rhs) {}
~Base();
};

void f() {
Base b;
};

The compiler shouts: no appropriate default constructor available

But when changing it to:

void f() {
Base b();
};

it compiles. Why?

The compiler is correct. A default constructor either takes no
parameters or has default values for all of the parameters, hence
enabling the default constructor call with no parameters or using the
already defined default parameters. Hence any one of the following is a
valid default constructor:

Base() { .... }
Base(int n = 7) { .... }
Base(char *name = NULL, unsigned id = 0) { .... }

JB
 

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

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top