[Gtk-sharp-list] Gtk# constructors

Jonathan Pryor jonpryor@vt.edu
18 Feb 2003 16:38:17 -0500


The C# compiler only provides a default constructor if the class
contains no other constructors.  So this:

	public class A {
	}

is the same as this:

	public class A {
		public A () {}
	}

However, as soon as you provide a constructor for the class, the default
is not provided.  So the following class declaration only contains 1
constructor (there is no default constructor):

	public class B {
		public B (string s) {}
	}

The only exception to this is for structures, which *always* have a
default constructor automatically provided.  In fact, structures are not
permitted to provide a default constructor.  However, structures can't
be used as a base class, so they can be ignored for now.

If GLib.Object() isn't really needed (as per the Charles Iliya
Krempeaux' guess), then it should be removed, as the class would have no
default constructor without it.

Furthermore, making a constructor private prevents derived classes from
calling *that* constructor.  If other (non-private) constructors are
available, they can still be called by derived classes.  So this is
perfectly kosher:

	class B {
		// not strictly needed, due to existence of protected 
		// constructor...
		private B () {}
		protected B (string s) {}
	}

	class D : B {
		public D () : base ("D class") {}
	}

 - Jon

On Tue, 2003-02-18 at 16:08, Charles Iliya Krempeaux wrote:
> Hello,
> 
> On Tue, 2003-02-18 at 06:57, Lee Mallabone wrote:
> 
> [...]
> 
> > 3: protected HBox() : base(){}
> 
> [...]
> 
> > Number 3 looks really odd - I followed the class hierarchy up to
> > GLib.Object, and its constructor just does:
> > 
> > public Object () {
> >    needs_ref = false;
> > }
> > 
> > which means, (as far as I can tell), that the internal Gtk C object
> > Handle is never instantiated, so you end up with an object that will
> > probably crash if you call instance methods on it.
> 
> Notice that this constructor has a "protected" access level.  That
> means that others can't call it.
> 
> I'd guess that this is declared so that C# doesn't automagically create
> a default constructor for us.  In other words, if we did not create
> a constructor with the signature:
> 
>     HBox()
> 
> ourselves.  Then C# would create one for us.  And the one it
> created would be "public".  And others would be able to call it.
> (Which we don't want.  So we created one ourselves that was 
> "protected".)
> 
> (Although, if we don't want other to call it, I'd probably make
> it "private" instead of "protected".  But then again, if you didn't
> do that then subclasses of it couldn't call it.  I don't know if
> that is important or not though.  Mike, is it???)
> 
> 
> See ya