views:

55

answers:

4

Hi, If I create the variable with type of a class, what is the actual value I will initialize it with? I mean - the int is initialized with value of that type that is number. But in the terms of technical precision, what happens when I create new instance of class?

class a
{
}
class b
{
  a InstanceOfA;
    InstanceOfA=new ();  //which what I initialize the variable?
}

Hopefully you will get my point, thanks

A: 

I'm not sure I got what you're asking, but if I did-
When you initialize a class, it's name is assigned it's reference address.
So when you write

InstanceOfA = new a();

InstanceOfA gets an address in memory (on the heap..) for an object of type a.

Oren A
+3  A: 

You want to create a new instance of class a. Here's an example, with the classes renamed to ease reading.

class MyClassA {
}

class MyClassB {
    MyClassA a = new MyClassA();
}

If your class a requires some initialization, implement a constructor for it:

class MyClassA {
    public MyClassA() {
        // this constructor has no parameters
        Initialize();
    }

    public MyClassA(int theValue) {
         // another constructor, but this one takes a value
         Initialize(theValue);
    }
}

class MyClassB {
    MyClassA a = new MyClassA(42);
}
qstarin
A: 

You're probably after something like this:

public class A
{
}

public class B
{
    public static void Main(string[] args)
    {
      // Here you're declaring a variable named "a" of type A - it's uninitialized.
      A a;
      // Here you're invoking the default constructor of A - it's now initialized.
      a = new A();
    }
}
Ben
A: 

Member variables of a class is initialised with the default value of their type. For a reference type this means that it's initialised to null.

To create an instance of the class, you simply use the class name:

InstanceOfA = new a();
Guffa