[C++] Calling copy constructor of base class

Started by
1 comment, last by Decrius 15 years, 6 months ago
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.
[size="2"]SignatureShuffle: [size="2"]Random signature images on fora
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.
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 :)

[size="2"]SignatureShuffle: [size="2"]Random signature images on fora

This topic is closed to new replies.

Advertisement