Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

class Parent{

};

class Child:
   public Parent
{

}

void Func(Parent*& param)
{

}

Child* c=new Child;

Func(c); //error
like image 983
lovespring Avatar asked Dec 09 '22 12:12

lovespring


1 Answers

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.

like image 54
Steve Jessop Avatar answered May 18 '23 17:05

Steve Jessop