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

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

class Der : public Base {
    //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) {

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.

  • "However I wish to implement a constructor for a base class where the argument is a der class." If you need to do that, then something has gone terribly wrong in your code's structure. That's a pretty big violation of OOP guidelines. Base classes (when used for OOP purposes) should never need to know about a particular derived class instance. – Nicol Bolas Jan 31 '17 at 18:31
  • Uff... What I want to understand is basically whether or not I need to implement anything special to perform casting from derivate class to base class. I mentioned the constructor because that's the usual way to implement casting. – user8469759 Jan 31 '17 at 18:36

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.

  • It's exactly just a matter of inherit only operation, I basically want to change the interface (because the way I manipulate the data member can change) and then I want to be able basically to perform the casting, which in this context is just the interface I want to change, there's actually no data I want to copy. – user8469759 Jan 31 '17 at 17:07

I can't see a way around passing a Der object into the Base class constructor, unless you want to into casting. But that starts to make things complicated and unreadable.

  • I don't understand, can you elaborate? I'm not sure I made understandable what I'm trying to achieve. So if something is not clear, please tell me I'll add more information. – user8469759 Jan 31 '17 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.