Inheritance issue

BlitzMax Forums/BlitzMax Programming/Inheritance issue

Jim Teeuwen(Posted 2006) [#1]
This is boggling my mind.
Either my brain has died, or something has changed with the inheritance. Because the way I find it behaving now kindof defeats the whole purpose of having Inheritance in the first place.. anyhoo. examples:

SuperStrict

Type A
	Function Create:A()
		Local _a:A = New A;
		Return _a;
	End Function
End Type

Type B Extends A
	Method Foo()
		Print("blah");
	End Method
End Type

'// Scenario 1
Local myB:B = A.Create();   '// Compile Error - Cannot convert from A To B

'// Scenario 2
Local myB:B = B.Create();   '// Compile Error - Cannot convert from A To B

'// Scenario 3
Local myB:B = B(A.Create());   '// Compiles, but...
myB.Foo(); '// Unhandled Exception:Attempt To access Field Or Method of Null Object

'// Scenario 4
Local myB:B = B(B.Create());   '// Compiles, but...
myB.Foo();  '// Unhandled Exception:Attempt To access Field Or Method of Null Object


These scenarios are the same with and without either Strict or SuperStrict.

It seems that casting objects back and forth does not work as it should. Does this mean I have to recreate all the Create() functions in every single subclass of A that I write? this has its own disadvantages. Lots of double code which should be solved by the inheritance. And as it stands, I can not treat an instance of B as an instance of A, not even after casting it with A(myinstance), as this threows the Null Reference Error.


Grey Alien(Posted 2006) [#2]
You have to make a create method in B either called Create with the same params, or if needing different params, call it SpecialCreate of something. You can't call Super.Create because it returns the wrong type. Typecasting won't work either as you've found out as you are forcing it to be a type it shouldn't be.


Who was John Galt?(Posted 2006) [#3]
[EDIT] Pipped at the post by Grey

You can use a B where an A is expected because the inherited entity contains all the stuff the parent has, but not the other way round, as you're trying.

So you will have to re-write your create functions.

In the last example, you're creating an A and casting it to a B - but the A doesnt have a foo method, hence the exception accessing it.


Jim Teeuwen(Posted 2006) [#4]
yes. I think i get the idea. ill just have to copy the Create functions and replace A with B. that seems to work.

Anyhoo, don't drink and code at the same time. It's bad for the brains.


H&K(Posted 2006) [#5]
Overriding Create() (BRL Forums)


Paposo(Posted 2006) [#6]
Hi.

Sorry my bad english

The inheritance allow use the inherited class in all vars defineds as parent class.
Not is posible use te parent class in vars defined as inherited class.

The create function in A make an object type A
The B class inherit create from A and this make an A type, not an B type.

Bye,
Ramon