0

I wrote this.

class A {   };

class B : public A
{
public:
    static B Convert(const A &a) { return static_cast<const B&>(a); }
};

int main()
{
    A a;
    B b = B::Convert(a);
}

But I would like to have this, do you know how?

B b = a.Convert();

Thank you in advance for your answers! ^^

  • Seems you are being asked to write a constructor for `B` that has `A` as it's argument. Not clear to me what the point of the quuestion is. – john Jun 13 '20 at 11:25
  • I just want to write this B b = B::Convert(a); in this form B b = a.Convert(); –  Jun 13 '20 at 11:31
  • That's impossible in valid C++. Since A is a base class of B it's not possible to convert from A to B. Mind you, your existing code is invalid as well. – john Jun 13 '20 at 12:49

1 Answers1

0

Generally I would say, don't do this. Use dynamic_cast<B*>(&a) instead See this post

But if you can check if a is of type B, you could implement it as follows:

class A {
    // ...
    B& Convert() { return return static_cast<B&>(*this); }
}

BUT be very care full to check if this is even a valid conversion otherwise you might get undefined behaviour during runtime !!!

Flo
  • 161
  • 1
  • 6