Jump to content
  • Advertisement
Sign in to follow this  
Decrius

[C++] Calling copy constructor of base class

This topic is 3638 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

I have a base class and it's derived class, when I use the copy constructor, I want the whole object to be copied, not just the derived class. By default, when I call the copy constructor of the derived class, it will call the constructor of the base class. I want it to be entirely copied...and it shouldn't call the constructor. How would I do this? This is what I did until now, but it will still call the constructor and won't work for base classes with virtuals:
    Derived::Derived(const Derived &instance)
    {
        Base::Base((Base &) instance);
    }
How do you guys do this? Or is this not how the copy constructor is supposed to work? Thank you in advance.

Share this post


Link to post
Share on other sites
Advertisement
By default the copy constructor of the derived class will call the base class default constructor. You don't want that, you want to call the base class copy constructor right?

Derived::Derived( const Derived &instance ): Base( instance )
{
// copy Derived members here
}


Afaik the example you posted is first calling the default base constructor and then you are calling the base copy constructor to create a temporary. This copy-constructed temporary will be destroyed at the end of that statement.

Share this post


Link to post
Share on other sites
Quote:
Original post by Icon
By default the copy constructor of the derived class will call the base class default constructor. You don't want that, you want to call the base class copy constructor right?

*** Source Snippet Removed ***

Afaik the example you posted is first calling the default base constructor and then you are calling the base copy constructor to create a temporary. This copy-constructed temporary will be destroyed at the end of that statement.


Yes, exactly! I was looking at the debug output and I noticed there was a temporary being made and destroyed. This makes sense :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • 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!