C # inheritance base class reference

class Base { //... public int i = 5; } class Drifted : Base { //... public int b = 10; } Base ObjectOrReference = new Drifted(); 

So Base ObjectOrReference; refers to the base type. When we write Base ObjectOrReference = new Drifted(); , it becomes an object, because, using the "new", we allocate memory for it? Or is he still referencing, and if true, what type is he? Direct question: "Is the object ObjectOrReference ?"

+4
source share
5 answers

This is another link, a pointer to an object on the heap. It has a Drifted type.

Even if your reference is of type Base , the base object is Drifted , and any overridden members of the derived class Drifted will be used instead of those that are on Base , even if you try to use Base .

When hiding a member using the new syntax, if you have a reference to a base type, it bypasses any derived classes that hide members.

An overview can be found on the Internet using Googling for "C # Reference Types." I looked through this, it looks like useful:

http://www.albahari.com/valuevsreftypes.aspx

+12
source
 Base ObjectOrReference = new Drifted(); 

with this, you created an instance of Drifted , but you reference the reference variable Base ObjectOrReference . Currently, options are limited to what is available in Base . If you want to, say, access int b in Drifted , you will have to give it to Drifted

+7
source

Yes, ObjectOrReference is an object and a valid object.

This is an object of type Drifted . This is the basic concept of object-oriented programming, in which the / ref pointer of the base class ( ObjectOrReference in your case) can contain / reference the object of its derived classes ( Drifted in your case), so it is not an error and is a valid object of the Drifted type

+7
source

This will always be a reference. Think of object variables as pointers / references. Although the actual creation / distribution of objects occurs on the heap, links are created in the local space of the stack.

+6
source

You created an instance of an object of a derived class, but reference its memory location through its reference type of the base class (ObjectOrReference). A reference to an object is known only to a member of its type (i.e., in its base class) and is completely unaware of a member of its derived class. This way you cannot access a member of the derived class, and you cannot enter text here since we are talking about inheritance

+1
source

All Articles