473,735 Members | 2,049 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.WriteLi ne("A");
}

} // end class A


class B : A
{
public B() : base()
{
Console.WriteLi ne("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/z2sM4qf2WEQIzAQ CgkP3vbB5lNJotB 1/9WXSt3+jQnb4Anj ek
6jRR6opsxA7UIqL slbD53ugg
=JHPs
-----END PGP SIGNATURE-----
Nov 16 '05 #1
9 2367

-----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/z2sM4qf2WEQI8rQ Cfb4mhPSr/A5F5AIpWSABplz/mmHkAoKTN
mJYor2zowLZYrtm EXJqjbY81
=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.WriteLi ne("A");
}

} // end class A


class B : A
{
public B() : base()
{
Console.WriteLi ne("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/z2sM4qf2WEQJuFA CeMVYLBnRQbzcMZ qpvsVjR5GvfX6kA njRF
ODAEOY3kUvgxUG2 LFJ3ZnJez
=zC3c
-----END PGP SIGNATURE-----
Nov 16 '05 #4
Player <gu***@My.email .address.scum.c om> 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.co m>
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.c om> 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/z2sM4qf2WEQIwog CgiBgTy9/F8cuYVId7Y/jctq2Xz7AAnjHX
Wzbn0aqucB33we3 6GGTaxOZt
=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/z2sM4qf2WEQIYCw CfYfKmelVf2eKYQ hH+r3j9FwlLNxoA oNHj
ilUwfWyEwvXvkbz GrZ3bm/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.WrteLin e("A");
}
} // end class A
class B : A
{
public B() : base()
{
}

public override void myMethod()
{
Console.WriteLi ne("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/z2sM4qf2WEQKBWg CfeUehgq3hJIMpe 69DDwQDEguCPh8A nR/A
813v8OmJFUknYyR 5uYp6EMxL
=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.WrteLin e("A");
: }
: } // end class A
:
:
: class B : A
: {
: public B() : base()
: {
: }
:
: public override void myMethod()
: {
: Console.WriteLi ne("B");
: }
: } // end class B
:

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

iQA/AwUBQYZ/QC/z2sM4qf2WEQIVmA CdF0YN1V+G6MCqI cJfwgtzy54P4O0A nRW0
IVkmhzM2ovFqyxi njbtKQ/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
2258
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 classes A, ... typedef A * APtr;
3
1874
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 methods back in the object that created it (the code above). Is there some attribute, method, or whatever within the dialog object that provides such access or do
7
1596
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 help at mastering my craft. What I am trying to do is best illustrated in code: public class TBase
2
2016
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
2714
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 inherit from a QuickFix.Application class. I have this object: private static SocketInitiator qfxInitiator; When instantiated, its constructor need a "QuickFix.Application" object.
4
4167
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? class Parent { Parent::Parent() { child = new Child( this) }; Child *child; };
10
2738
by: Angel Tsankov | last post by:
Hello! Is the following code illformed or does it yield undefined behaviour: class a {}; class b {
14
2119
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 couldn't compile the class. Any hints that I'm missing? Header File: #ifndef __Calc_h__
5
588
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 following class as an example: class Test { public: static void print_message(char *s) { printf("%s\n", s); } void delete_me()
0
8964
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8786
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9466
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9327
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8202
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6049
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4823
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2740
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2190
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.