Reputation: 4093
I am experimenting with VBA's Interfaces, and I'm a bit annoyed. Most of what I've read on the topic suggests using Interfaces as a means to achieve polymorphism, which seems to work in some of my use cases. Unfortunately, I have run into an issue.
I created a class module to define my interface iCanvasObject
I then created a class cTable
that implements all methods in iCanvasObject
. So far so good, everything works as expected.
The issue occurs when I define a method specific to cTable
, and not part of iCanvasObject
. Even if its Public
I can't seem to access it from a variable dimensioned as iCanvasObject
, but instantiated as cTable
.
Dim tbl As iCanvasObject
Set tbl = New cTable
Its not visible in IntelliSense which I could live with, but when I try to simply call the method directly, VBA complains of a Method or data member not found
error. Even though this variable is definitely of type cTable
Is there a way for me to create methods specific to cTable
that I can call while still utilizing the polymorphism benefits of the interface? Said another way, if I dimension a variable as iCanvasObject
, am I strictly limited to whats defined in this interface?
Upvotes: 3
Views: 1860
Reputation: 591
You will have to cast. The good news is that classes can implement multiple interfaces.
What I typically do in this situation is I include in my class definition an asSomeInterface method that returns an instance of the class as whatever interface the class is implementing.
Additionally, it should be noted that you can cast from one interface type to another, and VBA will allow this as long as the instantiated object implements both.
Upvotes: 1
Reputation: 6120
If you need to access the cTable methods and properties, you will need to "cast" it back to a cTable temporarily. You can do this as follows:
Dim tbl As iCanvasObject
Set tbl = New cTable
'Access iCanvasObject methods/properties through tbl
Dim tempTable As cTable
Set tempTable = tbl 'Implicitly casts tbl to a cTable because tempTable is an object reference to a cTable.
'Access cTable methods/properties through tempTable
Upvotes: 2
Reputation: 12847
The answer is simple, if you want access to methods that are not part of the interface you have 2 options:
Dim tbl As cTable
or Cast:
Dim tbl As iCanvasObject
Set tbl = New cTable
Dim tbl_i As CTable = DirectCast(tbl, cTable)
But I'm not sure VBA supports casting so option #1 is probably better.
Upvotes: 2
Reputation: 35260
That's the way polymorphism works. If you declare it as iCanvasObject
then that is what it is, and thus, it doesn't have any of the members of ctable
that don't come from iCanvasObject
, unless you cast it as a cTable
.
This has nothing to do with the fact that you're using VBA.
Upvotes: 8