Home > OS >  Is downcasting safe in C , if the derived class only have new methods(no new variables)?
Is downcasting safe in C , if the derived class only have new methods(no new variables)?

Time:04-14

struct Foo{
    Foo(int val) : i(val){}

    Foo &operator=(const Foo&){ //... }

    void fun(){}

    int i;
    std::string s;
};

struct Bar : public Foo{
    Bar(int i) : Foo(i){}

    Bar &operator=(const Bar &other){ 
        this->Foo::operator=(other);
        return *this;
    }

    void new_func(){}
}

Take this piece of code for example, Bar is extended version of Foo, and no additional member variables are added. Any danger downcasting a Foo instance to Bar, and use the extended function?

Also, is there a way to allow me downcast Foo to Bar implicitly, so I don't have to write static_cast all the time?

CodePudding user response:

Any danger downcasting a Foo instance to Bar, and use the extended function?

If the instance manipulated was created as a Bar, upcasted to a Foo, and then downcasted back to a Bar, all is well.

If you take an instance constructed as a Foo and downcast it to a Bar, you're both feet in Undefined Behaviour territory.


Is there a way to allow me downcast Foo to Bar implicitly

No, fortunately no. By design. But you can create a Bar from a Foo provided Bar has a copy constructor taking a Foo.


I want to extend a class from a thirdparty library, with new functionality. And the original class is used all over the place. I want to keep them untouched, and only use the extended class, in the new code

Inheritance is not the paradigm you are looking for. enter image description here You're looking for something simpler like composition.

CodePudding user response:

Any danger downcasting a Foo instance to Bar, and use the extended function?

It's safe only if the Foo instance is an ancestor sub object of a Bar instance. In any other case the behaviour of the program is undefined.

If you were to add a virtual function into Foo, then it would be safe to attempt dynamic cast, but it would fail in the latter case.

Also, is there a way to allow me downcast Foo to Bar implicitly

No.

  • Related