question about default constructor

J

July

consider the following code:
class A {
public:
A(int i) : i(i) {
}

private:
int i;
};
int main()
{
A a;

return 0;
}

The code cannot compile because there is no default constructor of
class A, but the book says that "the compiler will generate the default
constructor if you don't define it"

What's wrong ?
 
J

Jim Langston

July said:
consider the following code:
class A {
public:
A(int i) : i(i) {
}

private:
int i;
};
int main()
{
A a;

return 0;
}

The code cannot compile because there is no default constructor of
class A, but the book says that "the compiler will generate the default
constructor if you don't define it"

What's wrong ?

I beleive it's actually, "the compiler will generate a defautl constructor
if you don't define any constructor".
 
A

Alf P. Steinbach

* July:
the book says that "the compiler will generate the default
constructor if you don't define it"

Which book is that (so that others can avoid it)?
 
B

benben

consider the following code:
class A {
public:
A(int i) : i(i) {
}

private:
int i;
};
int main()
{
A a;

return 0;
}

The code cannot compile because there is no default constructor of
class A, but the book says that "the compiler will generate the default
constructor if you don't define it"

What's wrong ?

The standard goes "If there is no user-defined constructor for class X, a
default constructor is implicitly declared."

Well, you declared (and defined) a constructor indeed, so the compiler won't
synthesize the default constructor for you. Not that the quote above didn't
say "if there is no user-defined DEFAULT constructor...".

Regards,
Ben
 
J

Jaspreet

July said:
consider the following code:
class A {
public:
A(int i) : i(i) {
}

private:
int i;
};
int main()
{
A a;

return 0;
}

The code cannot compile because there is no default constructor of
class A, but the book says that "the compiler will generate the default
constructor if you don't define it"

What's wrong ?

In this case you will **not** have a default constructor generated by
the compiler since you have defined your own paramterised constructor.

Probably the next sentence/chapter in the book would have been that
"the compiler generates a default constructor if and only if you do not
have any constructor declared/defined in your class".
 

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,301
Messages
2,571,549
Members
48,295
Latest member
JayKillian
Top