Can I avoid overriding inherited methods with OOP

Hello,

Using OOP I’m trying to call both a sub (derived) class method and a super (base) class method in one go to minimize repeating code.

However, the issue is methods implemented in the derived class override the base class and any attempts to access the base class from the derived class result in stack overflow.

What I have attempted:

-- The derived class

...

function class.new()
    local newClass = baseClass.new()
	newClass.BaseClass = newClass -- this feels wrong
	setmetatable(newClass, class)
		
	return newClass
end

function class:Destroy()
	self.BaseClass:Destroy()
	print("Destroying from child class")	
	setmetatable(self, nil)
end

...

I read about maids and how they can be useful in this situation, but I’m hoping there is a simpler way. :pray:

Maybe I’m overthinking this since I’m so used to C++ polymorphism.

Here is an C++ eqivalent problem/solution.

Thanks in advance!

1 Like

When you add a method that is similar to the base class and use self instead of the base class method it will use the derived class method something which we do not like, here is a TS example of solving it hopefully If I get your question correctly

https://roblox-ts.com/playground/#code/MYGwhgzhAEDuD2toG8BQ0PQOIFMAuAFAJQqrqYC+qVqokMAZvPNDgB544B2AJjAkjSZs+YqWHCIAVwAOOAE4A6XISLkMVCkA

super is the base class and self is the derived class

2 Likes

Hi, @FerbZzides That seems like the right TS solution but I’m having a hard time reading that syntax since not too familiar with Roblox TS. Can you provide the lua and metatables equivalant?

oops never mind seems that I can extract the lua in that playground

Got it working by doing this! Since the derived class has a reference to the inherited class
ex:

local class = {}
inheritedClass = require(script.Parent) -- here
setmetatable(class, inheritedClass)
class.__index = class

I can call the inherited method Destroy() and pass self like this

function class:Destroy()
	inheritedClass.Destroy(self)
	print("Destroying from class")	
	setmetatable(self, nil)
end

Thank you @FerbZides for the suggestions

2 Likes