-1

I have a base class and derivative class, e.g :

class Base {
 public:
  Base();
  virtual doSomthing();
};

class Derivative : class Base {
 public:
  Derivative();
  virtual doSomthing();
};

I know that if I want to change at runtime from the father to son I will do

Derivative& newDer = dynamic_cast<Derivative&>(baseInstance)

my question is how I can do the opposite operation - change from son to the father?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Bizzu
  • 449
  • 3
  • 17
  • 5
    There's no specific cast operation needed. The compiler resolves that automatically. – user0042 Sep 16 '17 at 14:43
  • 1
    What is the reason you need to do this, a derived class has all the properties of it's base. And there normally is an implicit derived-to-base conversion happening at compile-time when you create a pointer or reference to a base class, but assign a derived class. – Carl Sep 16 '17 at 14:44
  • You can simply assign. A Derivate **is a** Base. –  Sep 16 '17 at 14:44
  • `Base &base = some_derivative` will do it. – Peter Sep 16 '17 at 14:44
  • 1
    [StackOverflow is not a replacement for a good beginner book.](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) And your question is a strong indication you have yet to read one. – StoryTeller - Unslander Monica Sep 16 '17 at 14:47
  • @peter _"... will do it"_ Not with the current example code. – user0042 Sep 16 '17 at 15:02
  • @user0042. The current example code would not compile, so that's a moot point. If the base class is accessible (e.g. inheritance is `public`, or the conversion is being done by a `friend`) the conversion of references from derivative to base is implicit. – Peter Sep 16 '17 at 15:05

1 Answers1

2

There's no specific cast operation needed. Any Derivative& automatically can be passed for a Base& if they are really have that relation like in

class Derivative : public Base {
                // ^^^^^^
 public:
  Derivative();
  virtual doSomthing();
};

Supposed you tried to do that from a global public scope.


my question is how I can do the opposite operation - change from son to the father?

The inheritance relation needs to be accessible in the scope used though. Your example has private inheritance, and it won't work at the public scope.

As mentioned by @StoryTeller and @Peter it will work at the Derivative inner class scope with any class member function or friended function/class.

user0042
  • 7,917
  • 3
  • 24
  • 39