views:

66

answers:

3

In C#/.NET:

I have 2 concrete classes. Class A and B. Class B subclasses from Class A.

How many instances (objects on the heap) and references from the stack to the heap objects are created for each line of code:

  1. ClassB b = new ClassB();

  2. ClassA a = new ClassB();

Thanks!

+4  A: 

Going with the analogy that the object is a balloon and the reference is a string that is tied to the baloon, in each of the following cases there would be one balolon and one string:

ClassB b = new ClassB(); //one reference, one heap object
ClassA a = new ClassB(); //one reference, one heap object

Running both at the same time will therefore create two objects and two references.

EDIT Have a look at this IL generated from ClassB constructor:

.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  call       instance void InheritanceTest.ClassA::.ctor()
  IL_0006:  ret
} // end of method ClassB::.ctor

call instance void InheritanceTest.ClassA::.ctor() indicates that it calls ClassA constructor as a member function(not as a function on a member object). This is in line with my understanding about what happens with instances of inherited classes, that the derived class is simply all the members of the base class, followed by members of its own, similarly to C++.

Igor Zevaka
A colleague of mine has argued that creating an instance of ClassB will create 2 objects (ClassA and ClassB) because constructors of both objects were called. I want to know if this is correct
He is not correct, that's not how inheritance works in C#.
Igor Zevaka
Thanks. I better start diving into IL code more often.
A: 

IN the first case - you will have only one instance of class B. In the second case, you will have one instance of class B. The instance of class A will not be created in the second case.

devcoder
`new ClassB()` creates a new instance of ClassB, regardless. What happens to that instance is up to the program. In this case a reference to the instance is stored in a `ClassA` reference. But it's still an instance of `ClassB`
Matt Greer
@Matt, Thanks for pointing out. That was a typo. Corrected.
devcoder
A: 

It really depends on what members are in each class. Supposing they are empty classes, one reference per object, for a total of two. That is, creating a ClassB object does not create references to any more than itself.

If they have members, of course, there are additional references for the members, but I think that is not the gist of your question.

kbrimington