If I add default arguments to the end of my copy constructor, is it still considered a copy constructor? E.g. will it still be used in the places where a copy constructor would normally be used (or automatically generated).

I can verify that it works on one compiler (g++). That is, this does output the "copy ctor" message 3 times:

#include <iostream>

class Context
{
  // real thing actually has some methods
};

class A
{
  private:
    Context & m_context;

  public:
    A ( Context * context )
      :m_context ( MATT_DEREF ( context ) )
    {
      // probably do something with context here..
    }

    A ( const A & a, Context * new_context = 0 )
      :m_context ( new_context ? *new_context : a.m_context )
    {
      std::cout << "copy ctor\n";
      // probably do something with context here..
    }
};

void test ( A a )
{ return; }

int main ( void )
{
  Context c1, c2;
  A a1 ( &c1 );
  // implictly copying by passing as value
  test ( a1 );
  // explicitly copying in the same context
  A a2 ( a1 );
  // copying to a new context
  A a3 ( a1, &c2 );
  return EXIT_SUCCESS;
}

But, will this always work O.K.? are there any caveats/pitfalls etc?

Other alternatives considered:

- I can't have the generated copy ctor used, for various reasons (e.g. other pointers/reference members shouldn't be shallow copied ).
- I don't want to pass the pointer to "context" in later, because that makes other areas unpleasant. E.g. I need to use "context" in the constructor, and it's not meant to be trivially reseatable.
- I do want the rest of the copy constructors features (i.e. being able to initialize the object & its bases in order).
- I'd rather not have to write 3 constructors for every class like this.

The C++ Standard:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6 ). Example: X:: X(const X& ) and X:: X(X&, int=1) are copy constructors.

Other alternatives of... what?...

Ok, thanks.

Other alternatives meaning, the list I put of things that I could have done to avoid having to do this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.