Calling child class function from parent class

I tried setting an int in the child class and using it in the parent and that was fine, but I can’t get the same to work for a pointer. Here’s a simplified version of my code:

function Child:init()
	self.super:init() -- calls Parent:init()
	self.var = 2
	self.MyDerivedClass = self

function Child:Test()
	Msg( "in test" )

function Parent:init()
	self.MyDerivedClass = nil
	self.var = 1

function Parent:Function()
	Msg( self.var ) -- prints 2, the child variable value, as expected
	self.MyDerivedClass:Test() -- crashes. Why?

c = Child()
c:Function() -- call Parent:Function()

Any ideas what the problem is and more importantly, how I might fix it? All input is appreciated :slight_smile:

Does c = Child() work as constructor? I never used it like that.
And you are nowhere deriving Child from Parent in the code (did you forgot to add it? Maybe here lays the problem)

Anyway, if it works like I think (Child derives properly from Parent) you are doing nothing wrong.

self:Test() in Parent:Function() might work for Child-objects at least but I don’t see why it should fail with your method since self.MyDerivedClass will be the exact same as self for a Child-object calling the derived function “Function”.

Yep :slight_smile: It’s pretty neat.

Sorry. You’re right, I left this out of the example but it is in my own code.

Alright. If you say it should work then at least I know my method is solid. There must simply be something wrong with my code somewhere. I don’t want to post it because there’s quite a bit. I’ll reinvestigate to see if I overlooked something. I’ll post again if it persists. Thanks for having a look at it :slight_smile:

For this to work, do you use __call on the metatable or is it a thing of Lua calling ::init() automatically?

In C++ the solution would be to use a virtual method and in Lua the same applies.

In order to inherit you are taking a copy of the parents metatable and then overwriting that with the a copy of the childs metatable. The parent must know that the method exists in order to call it, in C++ you could use a pure virtual method as a placeholder for this method - The parent knows that it exists but it has no body and hence cannot be called. When you inherit from the parent, you overwrite this virtual method with the childs implementation of it, allowing you to call it. The same applies to a Lua implementation of object orientation.

In other words, you would also define a blank Test() method in the parent and call it as you normally would. The inheritance will automatically overwrite the Test() method with the childs Test() method and that would be called instead. This is the reason why you have to call self.super:init() inside of the childs init() method - The parents was overwritten in that object.

Hope that helps.