Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Constructor with default argument

35 views
Skip to first unread message

Daniel

unread,
Oct 10, 2018, 6:01:07 PM10/10/18
to
Consider the following:

class A
{
int n;
public:
A() = delete;
A(int n)
: n(n)
{
}
};

template <class T>
class B
{
T t;
public:
B(T t = T())
: t(t)
{
}
};

(1) B<A>(); // fails, as expected

(2) B<A>(A(1)); // ?

Is it for certain that the expression T() won't get evaluated in (2)?

Thanks,
Daniel

Öö Tiib

unread,
Oct 11, 2018, 1:51:52 AM10/11/18
to
On Thursday, 11 October 2018 01:01:07 UTC+3, Daniel wrote:
> Consider the following:
>
> class A
> {
> int n;
> public:
> A() = delete;
> A(int n)
> : n(n)
> {
> }
> };
>
> template <class T>
> class B
> {
> T t;
> public:
> B(T t = T())
> : t(t)
> {
> }
> };
>
> (1) B<A>(); // fails, as expected

You mean by being most vexing parse?

> (2) B<A>(A(1)); // ?
>
> Is it for certain that the expression T() won't get evaluated in (2)?

Yes.

Öö Tiib

unread,
Oct 11, 2018, 1:56:15 AM10/11/18
to
On Thursday, 11 October 2018 08:51:52 UTC+3, Öö Tiib wrote:

> > (1) B<A>(); // fails, as expected
>
> You mean by being most vexing parse?

Nah ... mea culpa ... it isn't most vexing parse.

Fraser Ross

unread,
Oct 11, 2018, 4:40:08 AM10/11/18
to
On 10/10/2018 23:00, Daniel wrote:
> Consider the following:
>
> class A
> {
> int n;
> public:
> A() = delete;
> A(int n)
> : n(n)
> {
> }
> };

The class has a constructor so the default constructor is not implicitly
declared defaulted and hence you did not need to declare it deleted.
Its an old rule but the terminology has changed.

Fraser.

Daniel

unread,
Oct 11, 2018, 9:58:36 AM10/11/18
to
On Thursday, October 11, 2018 at 1:51:52 AM UTC-4, Öö Tiib wrote:
> On Thursday, 11 October 2018 01:01:07 UTC+3, Daniel wrote:
> >
> > class A
> > {
> > int n;
> > public:
> > A() = delete;
> > A(int n)
> > : n(n)
> > {
> > }
> > };
> >
> > template <class T>
> > class B
> > {
> > T t;
> > public:
> > B(T t = T())
> > : t(t)
> > {
> > }
> > };
> >
> > (1) B<A>(); // fails, as expected
>
> You mean by being most vexing parse?
>
No, this fails because the template argument supplied doesn't have a default
constructor, so T() isn't defined.

> > (2) B<A>(A(1)); // ?
> >
> > Is it for certain that the expression T() won't get evaluated in (2)?
>
> Yes.

Just want to be sure that no compiler would evaluate
the default parameter (and hence fail) if an actual parameter was passed.

Daniel
0 new messages