Author Topic: Is it necessary to initilaize when defining a instance?  (Read 1762 times)

0 Members and 1 Guest are viewing this topic.

waterharbin

  • Guest
Is it necessary to initilaize when defining a instance?
« on: June 15, 2012, 04:27:26 AM »
Hi.
I always wondering what the difference between those codes:
Code: [Select]
Point3d firstPt;
Point3d secondPt = new Point3d();
Point3d thirdPt = new Point3d(100,200,300);
And what about other classes,like Line class? What exactly happens when those code get executed? And which is the best?

Delegate

  • Guest
Re: Is it necessary to initilaize when defining a instance?
« Reply #1 on: June 15, 2012, 05:49:00 AM »
First I will say Point3d is a struct and as such it is a value type.
Line is a class and as such it is a reference type.

I say this because it results in subtle differences in the first example:

Point3d firstPt;
Line line1;

This Basically tells the compiler the object type but does not instantiate the object.  However interestingly when you compile line1 will be null but firstPt will be instantiated to 0,0,0.   Though the compiler won't let you compile your code if you try to use firstPt before using a constructor.

Point3d secondPt = new Point3d();
Line line2 = new Line2();

Using the default constructor and creates an instance of the object with coords set to 0,0,0 and for the line obviously 0 length etc.

Point3d thirdPt = new Point3d(100,200,300);
Line line3 = new Line(secondPt, thirdPt);

Creates an instance of the object as per your variables.

Again if you try : Line line3 = new Line(firstPt, thirdPt); you get a compiler error even though firstPt compiles to the same as secondPt.

So I guess the first example is only good when you want to compare types as you still need to use the new constructor at some point??
To reduce overheads try to use third example??

Interesting to read other comments on this as I'm only learning.  :-D