0

If Child is inherited from Parent and overrides the function foo().

    Child c;
    Parent *p = &c;
    p->foo();

How does the compiler know the type of the pointer p, since we are only passing the address of c with no other information?

Does the compiler automatically change the type of pointer p and behaves the same as the following?

    Parent *p = new Child();
    p->foo();
Yibo
  • 1
  • 1
  • I think you want to add a compiling example. `Child c()` is a function that takes no parameters and returns a `Child`. – MSalters Nov 16 '21 at 09:34
  • This question also requires some clarification - the type of `p` is obviously `Parent*`. That's how it is declared. The initializer doesn't affect it at all. It would be a different matter if we wrote `auto p = &c`, in which case the initializer does determine the type. – MSalters Nov 16 '21 at 09:37
  • 2
    The type of the pointer doesn't change. You declared it as `Parent*`, that is its type. Period. At runtime, it *points* at a `Child` object in memory. Now, how a call to `p->foo()` ends up calling `Child::foo()` instead of `Parent::foo()` is an **implementation detail** of the compiler, but *most* compilers use virtual dispatch via a **vtable**, which is a table of method pointers that the compiler sets up your pointer to point at at runtime, then virtual calls are done using a couple of simple pointer dereferences. – Remy Lebeau Nov 16 '21 at 09:37
  • On a side note, `Child c();` is a function declaration, not an object declaration. Drop the parenthesis: `Child c;` – Remy Lebeau Nov 16 '21 at 09:39

0 Answers0