Instantiation vs inheritance

Scenario:-

class A;
  int a;
endclass

class B extends A;
  int x;
endclass

class C;
  intx;
  A a;
  function new();
    a = new();
  endfunction 
endclass

Questions-
1- What is the difference bw clas B & C ?
2- How much memory is allocated to Class B & C?

Let me answer the second question first - there is no memory allocated to either class B or C until they are constructed as objects, as below

B b_h;
C C_h;
initial begin
     b_h = new();
     c_h = new();
end

When you call the constructors, each returns a handle to an object that has two members. The object referenced by b_h has two int variables: a and x. The object referenced by c_h has an int variable x and a class variable a. The constructor of C calls the constructor of A, which happens to have one member, the int variable a. The handle to that object is stored in the class variable a.

So the memory allocated to class B & C objects are about the same (assuming that an int and a class variable take the same size). It’s just that calling the C constructor winds up constructing two objects, a class A and C object. The memory allocated for the class A object is not part of the memory for the class C object, it just has a handle or reference to the A object.

There are too many differences to answer your first question here, and the choice between inheritance and instantiation may have more to do with your use of class methods than class members. But I will show you one small difference when doing a simple copy of a class object.

When you make a simple copy of class, you copy each class member from one object to another object. For the B object, you copy the two int variables. But when you copy the C object you only copy the one int variable and the one class variable. The A object does not get copied. So you wind up with two C objects referencing the same A object. You many want to study up on deep copy versus shallow copy.

In reply to dave_59:

Thanks Dave,
the choice between inheritance and instantiation may have more to do with your use of class methods
Please explain how the choice between inheritance and instantiation affects the use of class method ?
provide few examples.

In reply to Vivek Kumar Rai:

Vivek,

The answer is too involved to go into discussion in this forum. I suggest you study up on some of the basic principles behind object oriented programming that are available online.