Copy Constructors and Inheritance

closed account (1yR4jE8b)
I have a bit of a conundrum: If have a base class with a properly defined (deep-)copy constructor, and I derive from that class and the only new member variable is a single pointer, and if I WANT the pointer to simply be a shallow copy of that pointer when it is copy-constructed...do I need to implement the copy constructor of the derived class? (Example below)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Bar
{
public:
     Bar(const Bar& other);  //this is implemented
private:
     //stuff here, some of it is also dynamically allocated memory
};

class Foo : public Bar
{
     //Is the compiler's default copy-constructor for this class sufficient?
private:
     int* ptr; //this is not deep copied upon class copy-construction
};
Can you use a debugger? It'd take about 5 minutes to write a small program, compile it, and debug it. Set a break point or add a cout to your base class's copy constructor and see what happens. It seems like you wouldn't have to but I'm not sure. I could be wrong. I am not clear on how you are going to properly destroy the object though. That could be tricky. if it is just a shared pointer in the derived class then you just have to make sure that somehow your program can shut down cleanly. Anyway I wouldn't wait around for an answer since you can test this in about 5 minutes.
closed account (1yR4jE8b)
I have tried not implementing the copy constructor, in the derived class and the default copy-ctor seems to work fine. I was just wondering about the semantics of a copy constructor, I thought Copy Constructors weren't supposed to automatically call copy constructors of base classes which is why I was asking.

I guess it's only automatic if the compiler gives it to you.
Correct.

If you provide your own copy constructor, then you have to ensure to call the base class copy
constructor otherwise the default one will be called.
closed account (1yR4jE8b)
sweet, now I know for sure. That's what I thought happened, I just wanted to make sure by asking.

Thanks, guys
Topic archived. No new replies allowed.