hi,
the tutorial makes this mysterious claim:
http://pike.ida.liu.se/docs/tutorial/oop/access_control.xml If a class has a constructor (that is, a method called create) it can be a good idea to declare it static. It is not supposed to be called except during the construction of the object, and if it is not static there may be some type incompatibilities in connection with inheritance.
what exactly is that supposed to mean?
i understand the use of static to protect create from access from the outside, but what kind of type incompatibilities can there be for inheritance? and how can static protect against them?
greetings, martin.
I expect the assumption is that a derived class will have a constructor with an extended/alternative (and thus incompatible) set of arguments. This is often the case with constructors, but not so often with normal overloaded functions (since that would make overloading less useful).
When actually used as a constructor (which is the only way to use it if declared static), there is no problem, because you normally know exactly which class you are instantiating, so there is no question which implementation of "create" will be called. However, if called as "o->create(...)", then you might have gotten "o" as a type polymorphic parameter, and normal overloading abiguities apply.
Of course, if you use strict typing, the compiler should be able to find all cases where a non-static function is overloaded in a non-compatible way, even if that function happens to have the name "create"...
And in fact, this might actually be what the sentence is referring to. If you have
class A { void foo() { ... } void create(int a) { ... } }
class B { inherit A;
void foo() { ... } void create(string b) { ... } }
then the compiler will not let you use an instance of class B where an instance of class A is expected, even though B is a subclass of A. This is because it does not fulfill the interface specified by A. If create is made static (in A), it is not part of the interface, and B can be used where A is expected.
ahh,
hiding create from the interface is a very good hint, thank you!
greetings, martin.
I'd add that it makes no sense to call the constructor repeatedly for an existing object (calls from subclass constructors being an exception). What would the purpose be? There is no convention that create() should be able to safely clean up and re-init an existing object so such situations would be better served by a separate method.
pike-devel@lists.lysator.liu.se