class question

  • Thread starter Thread starter Eddie Pazz
  • Start date Start date
E

Eddie Pazz

What's the preferred method, or does it matter?

class Foo
{
private MyType msg = new MyType();

Foo() {}
}

or

class Foo
{
private MyType msg;

Foo() { mytype = new MyType(); }
 
Eddie Pazz said:
What's the preferred method, or does it matter?

class Foo
{
private MyType msg = new MyType();

Foo() {}
}

or

class Foo
{
private MyType msg;

Foo() { mytype = new MyType(); }

The only difference occurs when an overridden method is called by a
base constructor, which might try to access mytype. You should avoid
calling overridden methods in constructors to avoid precisely this
confusion.

As to where you place the assignment - it's really up to you. Different
people find different styles more readable.
 
Hi Eddie,

In your little example there is no difference. It is up to you where you do
the initializations.
However in a real project it might has some impact.

So when you initialiaze type members upon declaration the compiler copies
that initialization at the begining of each and every constructor you have
declared for the type. Thus, if you have a lot of initiazlization code it
will go in every constructor. In addition if you call one cosntructor from
another you may end up with the same initialization code executed several
times

One restriction is that you can't use 'this' keyword during the
initialization upon declaration. As a result you may end up with part of the
variables initialized in the constructors part of them upon declaration and
IMHO this may hurt the readability of the code.

How I said It's up to you, but bare in mind some of those little things
 
Back
Top