473,320 Members | 1,990 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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


-----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-----
Nov 16 '05 #1
9 2334

-----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-----
Nov 16 '05 #2
Player wrote:
-----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;
}
}

--
Joerg Jooss
www.joergjooss.de
ne**@joergjooss.de
Nov 16 '05 #3

-----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-----
Nov 16 '05 #4
Player <gu***@My.email.address.scum.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
On Mon, 1 Nov 2004 08:15:48 -0000, "Player"
<gu***@My.email.address.scum.com> wrote:

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#.

Nov 16 '05 #6

-----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-----
Nov 16 '05 #7

-----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-----
Nov 16 '05 #8

-----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-----
Nov 16 '05 #9

-----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-----
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Ernst Murnleitner | last post by:
Dear Readers, Is it possible to forbid conversion from this or use of this in general except where it is explicitly wanted? Reason: I changed my program from using normal pointers to...
3
by: Ray Mitchell | last post by:
Hello, I am opening a modal dialog in the standard way using something like: ....all the standard setup stuff... dlg.ShowDialog(); I need the dialog object to be able to access some of the...
7
by: Daniel Ervi | last post by:
Hi All, I have a question for the group as I can't seem to come up with any suitable solutions. I'm not that new to programming or C#, but neither am I very fluent yet, so I'd appreciate any...
2
by: Sagaert Johan | last post by:
Hi i found this in an example class, but never saw this syntax before. thais was inside a derived class of a combobox public ComboBoxExItem() : this("") {
6
by: Marty | last post by:
Hi, I have a class that I modified to be static. It is now a public sealed class and all function are static, no more constructor but a init() function to do the constructor job. This class...
4
by: craig | last post by:
During construction of an object "parent", if you create a subobject that stores a pointer to the parent (through the "this" pointer), will that pointer be valid when the subobject is later called?...
10
by: Angel Tsankov | last post by:
Hello! Is the following code illformed or does it yield undefined behaviour: class a {}; class b {
14
by: Alexander Dong Back Kim | last post by:
Dear all, I used to use C++ programming language at all time but moved to C# and Java. Few days ago, I restarted studying about C++ with a very beginner's mind. I wrote a simple class and gcc...
5
by: WaterWalk | last post by:
Hello. The question about "deleting this inside the class's member function" is discussed many times in this group and in the "C++ FAQs". But I still have two more questions. 1. Take the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.