Copy constructor not in public interface.

This is something I tweeted about yet I felt it required a snippet to show what I meant, so here it is.


class foo
{
public:
	foo(int i):bar(i){}
	int bar;
private:
	foo(foo const&);//prevent copy constructor
};

int baz(foo const& f)
{
	return f.bar;
}
int main()
{
	return baz( foo(0) );
}

This will fail to compile when no language extensions are turned on; yet by removing the “private” keyword and therefore taking the unimplemented copy constructor into the public interface it will compile.

Advertisements

2 Responses to “Copy constructor not in public interface.”

  1. Christopher Currie Says:

    Does the standard mandate this behavior? It seems pretty dumb, especially if I use a named variable, it compiles just fine:

    class foo
    {
    public:
    foo(int i):bar(i){}
    int bar;
    private:
    foo(foo const&);//prevent copy constructor
    };

    int baz(foo const& f)
    {
    return f.bar;
    }
    int main()
    {
    foo f(0);
    return baz( f );
    }

  2. cppmyths Says:

    Christopher I would not argue against it being dumb especially since the constructor is not defined and not actually called, yet required to be available. The standard only says that it may be called as constant is applied after the constructor.

    12.1 :4
    A constructor shall not be virtual (10.3) or static (9.4). A constructor can be invoked for a const, volatile or const volatile object. A constructor shall not be declared const, volatile, or const volatile (9.3.2). const and volatile semantics (7.1.5.1) are not applied on an object under construction. Such semantics only come into effect once the constructor for the most derived object (1.8) ends.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: