1

I have a question. Say I have a class A, for which I'm perfectly happy with the default copy constructor.

Can I add functionality to this default copy constructor without re-writing all its work again?

Trivial example:

class A 
{
public:
A(int n) : data(n) { };
private:
int data;
};

Suppose I want to print the message "Copy constructor!" each time a copy constructor is called. For this simple case I would just write my own copy constructor, which takes charge of the shallow copy explicitly, and also prints out the message. Is there a way to add the message printing (or whatever other functionality I want) on top of the default copy constructor, without writing explictly the shallow coyp?

dbluesk
  • 265
  • 3
  • 10

1 Answers1

1

Suppose I want to print the message "Copy constructor!" each time a copy constructor is called. For this simple case I would just write my own copy constructor, which takes charge of the shallow copy explicitly, and also prints out the message.

Yes, you need to provide your copy constructor explicitely and add that printing out the message.

class A 
{
    public:
    A(int n) : data(n) { };
    // You need to add tis:
    A(const& A rhs) : data(rhs.data)  {
        std::cout << "Copy constructor!" << '\n';
    }
    private:
    int data;
};

Is there a way to add the message printing (or whatever other functionality I want) on top of the default copy constructor, without writing explictly the shallow coyp?

No, there isn't.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190