开发者

cannot pass a subclass pointer to a function when the function need a reference to the parent pointer, why?

开发者 https://www.devze.com 2023-01-27 11:55 出处:网络
class Parent{ }; class Child: public Parent { } void Func(Parent*& param) { } Ch开发者_StackOverflow中文版ild* c=new Child;
class Parent{

};

class Child:
   public Parent
{

}

void Func(Parent*& param)
{

}

Ch开发者_StackOverflow中文版ild* c=new Child;

Func(c); //error


Here's the reason why:

struct Parent {};

struct Child: Parent { int a; };

void Func(Parent*& param) { param = new Parent(); }

int main() {
    Child* c = 0;

    Func(c); // suppose this was allowed, and passed a reference to "c".
    c->a;    // oh dear. The purpose of a type system is to prevent this.
}

If you can change Func to take Parent *const &, that would be OK.


See the C++ FAQ item "21.2 Converting Derived* → Base* works OK; why doesn't Derived** → Base** work?".

Note that this is the same problem as converting Derived*& to Base*&.

Cheers & hth.,


This is by design.

c is not a Parent*, it is a Child*. To turn it into a Parent*, an implicit conversion is required. This implicit conversion generates a temporary Parent* object (at least conceptually), and a non-const reference cannot be bound to a temporary object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号