Assigning a derived class object to a parent class reference

I am always surprised when I see:

Parent ref = new Child();

where the Child class extends Parent.

  • What does an object look like refin memory?
  • How is the virtual method handled? non virtual?
  • How is this different from:
Child ref = new Child();
+5
source share
4 answers

What does an object look like in memory?

Your question is not clear. There are two corresponding memory locations. The variable is associated with the storage location. This storage location contains a link to another storage location.

The storage location of a variable is usually implemented as an integer of four or eight bytes, which contains a “managed pointer” —a memory address known to the garbage collector.

CLR. , , - . , .

(vtable) , , , .

? ?

, vtable, vtable .

vtable, .

...

, , , . , , , , .

, , , "" , . , , , , .

http://blogs.msdn.com/b/ericlippert/archive/2011/03/17/implementing-the-virtual-method-pattern-in-c-part-one.aspx

+6

ref Child. Child. , Child, Parent.

foo() , , ref. Parent ref = new Child();, Parent.foo(). Child ref = new Child();, Child.foo(). , # new Child.foo(), , Parent.

+2

, ref , Child. , (Child); , (Parent). Child ref = ..., Child, Parent.

, :)

0

(, Parent )

Parent ref = new Child();

Parent ref = new Parent();

, , Child, , .

, , , . , , , - , , .

, foo . foo Parent. , foo ( ). foo , foo Parent, , . , , foo , , ref , foo. , , foo

0

All Articles