Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

mrmrcoleman

Copy constructor with inheritance.

This topic is 5366 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello. If I have two classes, one is derived from the other ie. X is the ClassBase. Y is the ClassDerived : public ClassBase What is the correct way to provide a copy constructor for Y? Do I simply initialise with the values of the new object as I would in an ordinary constructor or do I have to define a copy constructor for the base class also and somehow call that too? Thanks in advance. Mark Coleman

Share this post


Link to post
Share on other sites
Advertisement
As long as you make the copy using type Y, it doesn''t matter what it inherits from. Default copy ctor''s are provided, and are automagically invoked for base classes.

What matters, is if you have pointers or handles to other resources in the class.

If you make the copy using a base class pointer (e.g. X x* = new Y, then you have to use a "deep copy" and this is typically done with a virtual method called clone.

Share this post


Link to post
Share on other sites
No, default copy constructor for base classes are not automagically invoked. Take this sample:

class Base {
public:
Base(int data = 0) : base_data_(data) {}
Base(const Base & other) : base_data_(other.base_data_) {}
virtual ~Base() {}
private:
int base_data_;
};

class Derived : public Base {
public:
Derived(int base_data, int derived_data)
: Base(base_data), derived_data_(derived_data) {}
Derived(const Derived & other)
: Base(other), derived_data_(other.derived_data_) {}
virtual ~Derived() {}
private:
int derived_data_;
};

int main(int, char **) {
Derived a(1, 2);
Derived b(a);
return 0;
}

When run b.base_data_ will equal 1. However, if I change the copy constructor for derived to:

Derived(const Derived & other)
: derived_data_(other.derived_data_) {}

Then b.base_data will equal to 0. When you define the copy constructor for a derived class, you should call the copy constructor of any base classes in the member initialization list.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!