Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a way to write an equality test for a VBA class with private members without exposing knowledge of the existence of those private members?
    text
    copied!<p>I do a fair amount of Excel VBA programming, but not a lot of it is object-oriented. Here is something that comes up every now and then that bugs me, and I'm wondering if there's something I'm missing. </p> <p>In VBA, say I have a class C defined with some private members like so:</p> <pre><code>'... Private hidden1_ As Double Private hidden2_ As Double '... </code></pre> <p>If VBA worked like C++ or (most?) other languages that support OOP, I could write a member function to do an equality test between instances of class C like this:</p> <pre><code>'Error: won't compile! Public Function equal(cinst As C) As Boolean equal = (hidden1_ = cinst.hidden1_ And hidden2_ = cinst.hidden2_) End Function </code></pre> <p>Of course, that won't compile in VBA because class member functions can only access private class members of the same instance they are invoked on. The best I've ever come up with to do this sort of thing is to instead define two member functions like this:</p> <pre><code>Public Function equalDef(hidden1 As Double, hidden2 As Double) As Boolean equalDef = (hidden1_ = hidden1 And hidden2_ = hidden2) End Function Public Function equal(cinst As C) As Boolean equal = cinst.equalDef(hidden1_, hidden2_) End Function </code></pre> <p>It's cumbersome, and it exposes knowledge of the existence of private class members, but at least it avoids actually exposing the <em>values</em> of private class members.</p> <p>Is this the best I can do?</p> <p>EDIT:</p> <p>As usual, after an answer, I've realized a better way to phrase the question. It was titled "Is there a cleaner way to write an equality test for a VBA class with private members?" when Dick answered it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload