Help with the, "this" initializer in a constructor.

P

Player

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hello all.

I am in the process of teaching myself C# and I think I am doing OK.

I have learnt how to how to call the right constructor of a class, if the
class has more than than one cosntructor, by making sure that each
constructor has a different signature. I have managed to learn that and get
it stuck up there in the old brain cells :)

But I am having a little difficulty with the, "this" initializer for calling
a classes OWN constructor rather than it's inherited base class cosntructor.

Example as follows, [and for clarity's sake I will mention that these
classes are book examples]

Say I have these two classes one a base class the other a derived one.

class A
{
public A()
{
Console.WriteLine("A");
}

} // end class A




class B : A
{
public B() : base()
{
Console.WriteLine("B");
}

} // end class B


Now I know in class B that it is, "explicitly" calling it's base class
constructor from the base class, "A" using the initializer, "base()" .

BUT what I don't know how to do is make sure that the derived class, "B"
calls ONLY it's own constructor via the use of the, "this()" initilaizer.

Can anyone help me with this please?

As I have said, I have learnt how to overload methods and constructors via
the different signature approach, I am just a touch confused on how to use
the, "this()" initializer within a constructor to make it's class call it
and not it's base class constructor, which it will do anyway if it's a
derived class, even without the explicit call.

Thanks in advance :)

Player







- --
***********
I hear, and I forget.
I see, and I remember.
I do, and I understand.
- -- Confucius
************
-----BEGIN PGP SIGNATURE-----
Version: PGP 8.0

iQA/AwUBQYXnOS/z2sM4qf2WEQIzAQCgkP3vbB5lNJotB1/9WXSt3+jQnb4Anjek
6jRR6opsxA7UIqLslbD53ugg
=JHPs
-----END PGP SIGNATURE-----
 
P

Player

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


See a quick...

B bee = new B();

Gives me as output..

A
B

When all I might want is..

B

Get what I mean??

Thanks again...

Player

-----BEGIN PGP SIGNATURE-----
Version: PGP 8.0

iQA/AwUBQYXrLi/z2sM4qf2WEQI8rQCfb4mhPSr/A5F5AIpWSABplz/mmHkAoKTN
mJYor2zowLZYrtmEXJqjbY81
=elHL
-----END PGP SIGNATURE-----
 
J

Joerg Jooss

Player said:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hello all.

I am in the process of teaching myself C# and I think I am doing OK.

I have learnt how to how to call the right constructor of a class,
if the class has more than than one cosntructor, by making sure that
each constructor has a different signature. I have managed to learn
that and get it stuck up there in the old brain cells :)

But I am having a little difficulty with the, "this" initializer for
calling a classes OWN constructor rather than it's inherited base
class cosntructor.

Example as follows, [and for clarity's sake I will mention that these
classes are book examples]

Say I have these two classes one a base class the other a derived one.

class A
{
public A()
{
Console.WriteLine("A");
}

} // end class A




class B : A
{
public B() : base()
{
Console.WriteLine("B");
}

} // end class B


Now I know in class B that it is, "explicitly" calling it's base class
constructor from the base class, "A" using the initializer, "base()" .

BUT what I don't know how to do is make sure that the derived class,
"B" calls ONLY it's own constructor via the use of the, "this()"
initilaizer.

If be mean by "ONLY" tp prevent calling a base class constructor, that's
impossible. It would leave you with an "incomplete" object.

Can anyone help me with this please?

As I have said, I have learnt how to overload methods and
constructors via the different signature approach, I am just a touch
confused on how to use the, "this()" initializer within a constructor
to make it's class call it and not it's base class constructor, which
it will do anyway if it's a derived class, even without the explicit
call.

As I said, that cannot work, and I wonder why you would ever want to do
that. The this() initializer has a complete different meaning, BTW. It is
used to call another constructor of the same class:

public class Foo {
private long id;

public Foo() : this(-1) {}

public Foo(long id) {
this.id = id;
}
}
 
P

Player

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Sorry I don't have a clue what you just said.

After creating an object of type B I am elft with two outputs...
A
B

When all I wanted was to create an object of type B with the output being...
B

Why do I have to have the output...
A
as well as
B ????


If I have those two classes in my previous original post, and all I want to
do is make an object of type..
B
then how do I do it so the only constructor I am calling is B's
constructor??

Surely getting the output..
A
B
is not wanted half the time, that means you have double the value in the
output..

All I want to do is call B's constructor on it own, and not have it calling
A's constructor as well.
Is that impossible with a derived class??

Player


-----BEGIN PGP SIGNATURE-----
Version: PGP 8.0

iQA/AwUBQYXwsS/z2sM4qf2WEQJuFACeMVYLBnRQbzcMZqpvsVjR5GvfX6kAnjRF
ODAEOY3kUvgxUG2LFJ3ZnJez
=zC3c
-----END PGP SIGNATURE-----
 
J

Jon Skeet [C# MVP]

Player said:
Sorry I don't have a clue what you just said.

After creating an object of type B I am elft with two outputs...
A
B

When all I wanted was to create an object of type B with the output being...
B

Why do I have to have the output...
A
as well as
B ????

Because at least one constructor in each type in the inheritence chain
has to be called. Otherwise, as Joerg says, you could end up with an
incompletely initialised object.
 
J

JuLiE Dxer

Sorry I don't have a clue what you just said.

After creating an object of type B I am elft with two outputs...
A
B

When all I wanted was to create an object of type B with the output being...
B

Why do I have to have the output...
A
as well as
B ????

That code looks a lot familar to that of Tom Archer's "Inside C#" in
Chapter 5 "Classes"

Anyway, the constructor of the base class is always called before any
code of the derived class is encountered. Since your "class B" derives
from "class A" you're stuck with its constructor's output.

Because there is only one constructor in each of these classes,
appending the "base()" constructor initializer doesn't alter the base
class' functionality. The base class' constructor is called anyway.

This constructor initializer is very handy if your "class A" has more
than one constructor. Suppose it has constructors like the following:

class A
{

// base constructor 1
public A ()
{
someValue = 0;
}

// base constructor 2
public A (int i)
{
someValue = i;
}

int someValue;

}


ok.. and suppose your "class B" derives from it and has its own
constructors similar to those of "class A"; one with an empty
parameter list () and one taking an int value (int i). You can tell
the compiler which base class ("class A") to call from your derived
class ("class B") depending on how your derived class is instantiated.
Also, suppose for some strange reason you don't want to utilitize the
base class' constructor taking no arguments "( )". You want the base
class constructor that accepts an int value to always be called. You
can specify that in your derived class' constructor. Example below.



class B
{
// constructor 1: calls base class taking an int value (42)
public B () : base (42)
{
// do nothing
}

// constructor 2: calls base class taking an int value
public B (int i) : base (i)
{
// do nothing
}

// calls "class B" constructor "public B (int i)"
public B (string s) : this (42)
{
// do nothing
}

}

As for the this() constructor initializer... You can tell the compiler
to call a different constructor in your derived class. Above, suppose
somebody passes a string value when initializing your "class B"
instead of an int, and you wish to instead have the "class B"
constructor taking an int called instead. That is what this() is for.
"this" points to the current class -- the derive class in this case --
and the (42) part tells the compiler we want to pass the int value of
42 to the class' constructor that takes an int -- constructor 2 above.

I was thrown for a loop when I first was introduced to the "this"
keyword back when I began learning Java in the 90s. It can be
confusing.

If I have those two classes in my previous original post, and all I want to
do is make an object of type..
B
then how do I do it so the only constructor I am calling is B's
constructor??

Don't extend from class A.

Surely getting the output..
A
B
is not wanted half the time, that means you have double the value in the
output..

All I want to do is call B's constructor on it own, and not have it calling
A's constructor as well.
Is that impossible with a derived class??


I don't recall seeing anything that allowed for that to be possible in
C#.
 
P

Player

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


Yes you're right, I am in the middle of reading, Tom Archer's "Inside C#".

I am still way confused on the issue, but seen as how it works anyways, I
guess the way I will look at it is that in the end even if the two
constructors are called, I will only be doing the work on the one I want to,
not on both..

I still no were near fully understand it, I haven't come across an
explanation that makes sense yet lol.

Thanks all the same for trying :)

Player

-----BEGIN PGP SIGNATURE-----
Version: PGP 8.0

iQA/AwUBQYX/gi/z2sM4qf2WEQIwogCgiBgTy9/F8cuYVId7Y/jctq2Xz7AAnjHX
Wzbn0aqucB33we36GGTaxOZt
=zl13
-----END PGP SIGNATURE-----
 
P

Player

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Looking at it from a -SPECIALISATION- view point, it kind-off makes sense
you know??

I mean just taking the angle of a simple Window class, for instance. From
that base Window class you get your basic window, but in order for you to
get more featured windows, you need to add a more specialised window class,
ie a derived class.
BUT...
in order for you to get your derived class, specialsied Window class, you
need the basic Base class Window also.

When thinking that way, it kind-of makes sense as I say.

But I ams till very confused lol.
Guess I must be thick eh lol.

Player

-----BEGIN PGP SIGNATURE-----
Version: PGP 8.0

iQA/AwUBQYYI+y/z2sM4qf2WEQIYCwCfYfKmelVf2eKYQhH+r3j9FwlLNxoAoNHj
ilUwfWyEwvXvkbzGrZ3bm/Xn
=WaQo
-----END PGP SIGNATURE-----
 
N

Nick Malik

No, you are not thick,

I encourage you to take a look at the Strategy pattern.

In this, your base class has a protected method that the base class
constructor calls.
In your derived class, you can override this method. This affects how your
base class initializes, because the base class now calls your overrided
method instead of the base method.

<<WARNING: this is uncompiled code from a person who is, for all intensive
purposes, "syntax impared". If you compile it, expect errors with my
apologies.>>

class A
{
public A()
{
dostuff();
}
protected dostuff()
{
Console.WriteLine("A");
}

} // end class A




class B : A
{
public B() : base()
{
}
protected override dostuff()
{
Console.WriteLine("B");
}

} // end class B


This is a powerful method for having a derived class modify the behavior of
the base class methods and is well documented in the patterns literature.

--- Nick
 
P

Player

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Yeah great thanks Nick Malik..

I went through what you said, read some more then experimented a little..

I came out of it with the following code...

class A
{
public A()
{
myMethod();
}

public virtual void stuff()
{
Console.WrteLine("A");
}
} // end class A


class B : A
{
public B() : base()
{
}

public override void myMethod()
{
Console.WriteLine("B");
}
} // end class B


Which DOES end up giving me the desired output, "B".

And I now understand why it's done like that, and why the base constructor
is always called, explicitly or not; But how you can override such
constructors and/or methods in order to achieve the desired goal :)

In the case above, it's still calling the base constructor, which is calling
the, "myMethod()" method, it's just that I am explicitly calling the base
constructor in my derived class, AND overriding the, "myMethod" in the
derived class, to get the desired result.

Thanks again to all - appreciated :)

Player



-----BEGIN PGP SIGNATURE-----
Version: PGP 8.0

iQA/AwUBQYZsqS/z2sM4qf2WEQKBWgCfeUehgq3hJIMpe69DDwQDEguCPh8AnR/A
813v8OmJFUknYyR5uYp6EMxL
=7q0b
-----END PGP SIGNATURE-----
 
P

Player

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Sorry, there was a slight erro in the code in the above post...
This is the correct code I came away with rather, and what made me realise
the in's and out's and why's of
why the base classes constructor is called.

Player


: class A
: {
: public A()
: {
: myMethod();
: }
:
: public virtual void myMethod()
: {
: Console.WrteLine("A");
: }
: } // end class A
:
:
: class B : A
: {
: public B() : base()
: {
: }
:
: public override void myMethod()
: {
: Console.WriteLine("B");
: }
: } // end class B
:

-----BEGIN PGP SIGNATURE-----
Version: PGP 8.0

iQA/AwUBQYZ/QC/z2sM4qf2WEQIVmACdF0YN1V+G6MCqIcJfwgtzy54P4O0AnRW0
IVkmhzM2ovFqyxinjbtKQ/Kb
=MGia
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top