Copy constructor in derived class

Mar 26, 2015 at 7:50pm
let's say if i have 2 classes like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 class base{
    private:
         int age;
         string name;
         string *namePtr;
    public:
         int getAge();
         string getName();
         base(int a, string b):age(a),name(b){
             namePtr = &name;
    };
}

class derive : public base {
    private:
         float salary;
    public:
         float getSal();
         derive(int a, string b, float c): base(a,b), salary(c){};
         derive(const derive& other); // copy constructor, how do i implement this one?
}


Do i do like:

1
2
3
4
5
6
7
8
9
10
11
12
derive::derive(const derive& other):base(other){
    salary = other.getSal();
};

or

derive::derive(const derive& other):base(other.getAge(), other.getName()){
    salary = other.getSal();
    derive.base::namePtr = &(name.base::name); //i don't know if this is right
    
};


i just want to know how many ways of doing it, and which is the best way to do it. such as with pointers and without pointers.
Mar 26, 2015 at 8:20pm
A constructor of class derive has access to the private members of class derive. Therefore, follow the yellow brick road laid out by the line 19.
derive::derive( const derive& other ) : base(other), salary(other.salary) {}
Mar 26, 2015 at 8:27pm

A constructor of class derive has access to the private members of class derive. Therefore, follow the yellow brick road laid out by the line 19.
derive::derive( const derive& other ) : base(other), salary(other.salary) {}


what about the pointer ? if i do it like this, isn't the copied namePtr pointing to the same address ?
Mar 26, 2015 at 8:49pm
You obviously have to implement a copy constructor for the class base too. A class has to be consistent whether or not it is derived from.
Mar 26, 2015 at 8:59pm
In your case derived copy constructor should look like that: derive(const derive& other) = default; as compiler-generated copy constructor does exactly what you need in this case.
Mar 26, 2015 at 9:46pm

In your case derived copy constructor should look like that: derive(const derive& other) = default; as compiler-generated copy constructor does exactly what you need in this case.


this make the copied object's pointer in the parent class pointing to a different address as well ?
Mar 26, 2015 at 9:53pm
This calls base class copy constructor first. If base class poorly implemented this is not derived class fault and not its responsibility to handle. If base class has proper copy constructor, derived will work properly too.
Mar 26, 2015 at 11:54pm
what if the base class doesn't have a user defined copy constructor ? what should i implement in the derive class's copy constructor ?
Mar 27, 2015 at 12:26am
what if the base class doesn't have a user defined copy constructor ?

If you cannot fix it, then don't use it.
Topic archived. No new replies allowed.