C++ – Subclass to super class casting, C++

cinheritancetype casting

Out of curiosity. Say I have a class with a data member:

class Base {
 public:
   //methods and constructor,set and get, operator overload etc
 private:
  int data;
};

class Der : public Base {
  public:
    //just overload of some of the methods in the base class, please note there's no data member
}

The idea is basically that I have many methods that are actually the same of the base class, and they would be the same for the derivate class. I guess I can define a constructor for the Der class like

Der::Der(const Base& x) {
   this->set_data(x.data);
}

However I wish to implement a constructor for a base class where the argument is a der class. Something like

Base a = 10;
Der b = 3;
Base c = b; //Here!!!
Der d = a;

My question is whether in the case I'm exposing I need to implement a constructor, or the copy constructor would the job for me automatically, given the relationship between base class and der class.

Best Answer

This will work as-is, by the usually-undesirable mechanism of object slicing.

That is, the derived class object b is implicitly cast to (a reference to) the base class, and then c uses the usual base-class copy constructor.

If this actually makes sense for you (ie, there are no other data members you should have copied from the derived class), then you have exactly zero work to do.