Subclass method, parameter type mismatch error

Hey there,

First I want to wish a Merry XMas to all of you.

Here’s my problem, I guess the answer is simple but I can’t find it.

I have a MyObject class (no super).
MyObject has a “copy” method, the “MyObject” to copy is passed as parameter and a “copy” is returned.
The method is defined as:

Function Copy(fromObj As MyObject = Nil) As MyObject Dim objCopy as New MyObject ... ... Return(objCopy)

I created a subclass AnotherObject with super = MyObject and many specific properties.

The problem is that I get a “type mismatch” error when using the Copy method:

Dim newObj As New AnotherObject
newObj = AnotherObject.Copy(oldObj)
newObj.specPropertyA = ...

newObj type is AnotherObject (subclass) and Copy is expecting and returning a MyObject type (super class)
There are multiple methods in MyObject that are using MyObject type, all these will give the same error.

How can I solve this ?

Thanks and regards.

You need to define the Copy method for AnotherObject so it returns an instance of AnotherObject rather than myObject. The way you have defined your classes and methods, AnotherObject.Copy(oldObj) will call the Copy method of myObject which returns an object of the wrong type.

Thanks Michael.
It would be fine if I had only one method but most of the MyObject methods are using MyObject as parameter or as return type.
I’d end up copying most the super class methods…

Is there another way to deal with that ? I merely want to have a bunch of specific properties for AnotherObject.

You can pass an instance of anotherObject to a method expecting an instance of myObject – no problem with that as every instance of anotherObject is also indirectly an instance of myObject. So I don’t see how using myObject as a parameter type would create issues in general. But it doesn’t work the other way round, so you cannot assign a direct instance of myObject to a variable of type anotherObject, which is what your code snippet attempts to do. The standard approach is to have copy methods for each subclass (which would be necessary in most cases anyway, as each subclass defines different properties to copy).

One solution: Supply both the original and copy as parameters:

Function Copy (orig As MyObject, theCopy As MyObject)
  theCopy.PropA = orig.PropA
  ...
End Function

dim orig as new AnotherObject
dim c as new AnotherObject
AnotherObject.Copy( orig, c )