www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - static functions?

reply "p0xel" <pixartist gmail.com> writes:
I pretty sure I'm an idiot.

[code]
class foo {
	public static int bar() {
		return 0;
	}
}
[/code]

How do I call bar() without creating an instance of foo? 
foo.bar() results in "Error: undefined identifier 'bar'"

I'm having a really hard time finding anything related to D in 
general.
May 20 2012
next sibling parent reply "p0xel" <pixartist gmail.com> writes:
This seems to work when the class is in the same file as main(), 
but if I move it to it's own file and use "import foo" it errors. 
What am I missing?
May 20 2012
parent Mike Parker <aldacron gmail.com> writes:
On 5/21/2012 6:32 AM, jerro wrote:
 On Sunday, 20 May 2012 at 21:19:14 UTC, p0xel wrote:
 This seems to work when the class is in the same file as main(), but
 if I move it to it's own file and use "import foo" it errors. What am
 I missing?

When you write "import foo;" and then foo.bar, the compiler thinks that you a referring to a global function bar in module foo. To call static function bar of class foo in module foo write foo.foo.bar(). Or you could write "import foo : foo;" to import just the class foo from module foo and not the entire module.

Or even better, name your module foo.d, and name your class Foo. Then... import foo; void main() { Foo.bar(); } That's also the general convention.
May 20 2012
prev sibling parent "jerro" <a a.com> writes:
On Sunday, 20 May 2012 at 21:19:14 UTC, p0xel wrote:
 This seems to work when the class is in the same file as 
 main(), but if I move it to it's own file and use "import foo" 
 it errors. What am I missing?

When you write "import foo;" and then foo.bar, the compiler thinks that you a referring to a global function bar in module foo. To call static function bar of class foo in module foo write foo.foo.bar(). Or you could write "import foo : foo;" to import just the class foo from module foo and not the entire module.
May 20 2012