...

View Full Version : Property Name Same as Method Name?



Trinithis
10-15-2007, 04:26 AM
I get a compile-time error doing:


class Foo {
private:
int length;
public:
Foo(int x) {
length = x;
}
int length() {
return length;
}
}

How can I have the length property and the length() function have the same name?

ralph l mayo
10-15-2007, 04:40 AM
No, it doesn't work that way, as your compiler already pointed out. Conventionally people prefix the method name with get_/get/Get.

felgall
10-15-2007, 10:10 AM
Properties hold values (NOUNS), methods perform actions (VERBS). Although the English language has a few words that can be both nouns and verbs, programming languages do not.

In any case is the length() method supposed to be setting the length or getting the length, the name doesn't say.

oracleguy
10-15-2007, 06:02 PM
Or you could prefix all your member variable names with 'm_' that way the function doesn't have the same name.

Afrow UK
10-16-2007, 01:14 PM
I tend to place g_ (C++) or just _ (C#) in front of globals.

Stu

ez4me2c3d
10-16-2007, 05:12 PM
In Ruby it would be as easy as this

class Person
def initialize(name)
@name = name.capitalize
end

def name=(name)
@name = name.capitalize
end

def name
puts @name
end
end

me = Person.new("Anthony")
me.name
me.name = "Elizabeth"
me.name
Output

Anthony
Elizabeth



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum