4

Following is a popular code:

class A
{
public:
    static const string TYPE = "AEvent";
    const string& getType() { return TYPE; }
};

Above code could be use like this:

if (aInstance.getType() == A::TYPE)
{ 
    ...
}

It's fine. But it's not intuitiveness. Did not? Look at the next code:

class A
{
public:
    static const string& getType() 
    {
        static const string TYPE = "AEvent";
        return TYPE;
    }
}
//Usage
if (aInstance.getType() == A::getType())
    ....

Of course, getType is static method but it's possible to access dot operator and It's more intuitively see to me.

How do you think about?

Shin Dongho
  • 238
  • 1
  • 13
  • 4
    I'm unsure of what the question is here. Are you asking about what the best practice is? – Maxpm Jan 19 '11 at 03:16

2 Answers2

4

If it's clearer to use obj.static_member (or method), then use it; this is often true when the type name is long, such as with templates. Otherwise use Type::static_member.

Fred Nurk
  • 13,952
  • 4
  • 37
  • 63
2

As long as you're returning a static variable from static method it should be fine. It doesn't matter if you call it using dot or resolution operator. Either way it's part of the object as well as the class which should give you the same static variable.

cpx
  • 17,009
  • 20
  • 87
  • 142
  • In fact, left side won't be evaluating so calling via NULL pointer is fine. – Joshua Jan 19 '11 at 03:33
  • 2
    @Joshua: [That's arguable](http://stackoverflow.com/questions/2474018/when-does-invoking-a-member-function-on-a-null-instance-result-in-undefined-behav). – GManNickG Jan 19 '11 at 03:35
  • Thanks @Dave18, @Joshua. You're right. It's even fine via NULL pointer!! – Shin Dongho Jan 19 '11 at 04:39
  • The question isn't whether it's fine but whether it's intuitive to do it that way (to promote readability, should the language even allow that?). – Zach Saw Jan 19 '11 at 06:38
  • @GMan: It's a static method. My compiler issues a warning. So does VB .NET incidentally (different language, same rule). – Joshua Jan 19 '11 at 16:15
  • @Joshua: I didn't say it wasn't a static method, I said it's arguable if it's okay. – GManNickG Jan 20 '11 at 03:34
  • It's always OK to call a static method through an instance pointer, even if the pointer is uninitialized. – Joshua Jan 20 '11 at 16:21
  • 1
    @Joshua: Have you even read what I linked to? On what grounds do you say that? – GManNickG Jan 20 '11 at 17:50
  • Your strict interpretation also requires that a function on the left side get called. Try it, it does not get called. – Joshua Jan 20 '11 at 18:21
  • 1
    @Joshua: What? Do you understand what undefined behavior is? – GManNickG Jan 20 '11 at 20:43