Tyler Jandreau
Tyler Jandreau

Reputation: 4335

How to use a copy constructor with a base class?

I'm confused about base classes and copy constructors.

Say I have a class

class A {
    public:
    A(int m) : m(m) { return; }
    virtual ~A() { return; }
    int m;
}

And a class that inherits this

class B : public A {
    public:
    B(int n, int m) : A(m), n(n) { return; }
    vitual ~B() { return; }
    int n;
}

When I copy class B, how do I ensure that the m value in class A is copied as well?

Upvotes: 3

Views: 1513

Answers (4)

Minimus Heximus
Minimus Heximus

Reputation: 2815

This code is your code just copy constructors are added with a class:

#include <iostream>

using namespace std;

struct Int
{

    Int ()
    {
    }

    Int(const Int&)
    {
        cout<< "Int copied" "\n";
    }
};


class A
{
    Int m;
public:
    A(Int m) : m(m)
    {

    }
    virtual ~A()
    {

    }

};

class B : public A
{
    Int n;
public:
    B(Int n, Int m) : A(m), n(n)
    {

    }


    virtual ~B()
    {

    }

};

void f(B)
{

}

int main()
{
   Int m,n;
   B b(m,n);

   cout<< "\n" "start:" "\n";
   f(b);
   cout<< "end";

}

Ubuntu Qt Creator Output says both are copied.

One can think there's a hidden member with type B in A and this hidden member can be initialized or copied as a usual member as in the above program with:

B(Int n, Int m) : A(m), n(n)

Upvotes: 0

paper.plane
paper.plane

Reputation: 1197

You should not return from a constructor/destructor, not even void.

Upvotes: -1

Mark Ransom
Mark Ransom

Reputation: 308528

The default copy constructor will copy all of the member variables, no matter whether they reside in the base class or a derived class.

If you create your own copy constructor for class B you will need to copy the class A members yourself, or better yet use the copy constructor for class A in the initializer list.

class B : public A {
    public:
    // ...
    B(const B & b) : A(b), n(b.n) {}
    // ...
};

Upvotes: 4

Neil Kirk
Neil Kirk

Reputation: 21813

The base copy constructor will be called before the derived copy constructor automatically. It's the same as for a regular constructor. (More accurately, the base constructor is called by derived initialization list before derived constructor continues). In your case, the default copy constructors are sufficient.

Be careful, however, that you do not copy a B into an A (search object splicing).

Upvotes: 1

Related Questions