How to use a copy constructor with a base class?
c++, copy-constructor
Solution
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) {}
// ...
};
Problem
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?