I tried for a while to realize it with virtual functions, when I realized that I don't exactly understand your reply. Let me give the actual code I am trying to modify:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
/*edited the code to make it more readable*/
class Rational
{
void Assign(Rational& r);
void MultiplyBy(Rational& r);
/*and some other members*/
};
class Monomial
{
public:
int NumVariables;
int* degrees;
Rational Coefficient;
void MultyplyBy(Monomial& m);
bool HasSameExponent(Monomial& m);
void CopyFrom(Monomial& m);
/*...and some more members...*/
};
class Polynomial
{
/*uses arrays of monomials. Here is the big lump of code.*/
};
void Monomial::MultyplyBy(Monomial& m)
{
assert(m.NumVariables == this->NumVariables);
for(int i=0; i< m.NumVariables;i++)
{
this->degrees[i]+=m.degrees[i];
}
this->Coefficient.MultiplyBy(m.Coefficient);
}
void Monomial::CopyFrom(Monomial& m)
{
this->init(m.NumVariables);
for (int i=0;i<NumVariables;i++)
{
this->degrees[i]=m.degrees[i];
}
this->Coefficient.Assign (m.Coefficient);
}
|
If I substitute the class "Rational" in the above code with a virtual class, say "ElementOfCommutativeRingWithIdentity", I wouldnt be able to declare class Monomial since the compiler wouldn't know how much memory to reserve for element in question.
As far as I understood your suggestion, you would advise me to create my ElementOfCommutativeRingWithIdentity elsewhere, and pass a pointer to it to my Polynomial class. That, however, would mean that
1) I must rewrite a solid portion of my code (which is actually ok by me)
2) The Polynomial class will be something like a nice object to "attach" to my ElementOfCommutativeRingWithIdentity object. In particular, my Polynomial class will not be able to allocate memory for its coefficients. This would lead to major structural changes in my code, which would, in my opinion, be more inconvenient than having me actually copy and paste my code and substitute the string "Rational" with the string "QuasiPolynomial" and the string "Polynomial" with the string "Polynomial2" (I would like to have "QuasiPolynomials" as coefficients of my polynomials, whatever that means).