Re: How to extend a class without redeclaring all its methods?
* Francois Grieu, on 04.08.2010 23:00:
In article<i3chnv$ke5$1@news.eternal-september.org>, "Alf P. Steinbach /Usenet"<alf.p.steinbach+usenet@gmail.com> wrote:
* Francois Grieu, on 04.08.2010 21:46:
Hello, I know C well, but not C++, and have a naive question.
I have a class defined by a library that I do not want to modify;
in my case the mpz_class of gmpxx.h (see<http://gmplib.org> ).
I want to add a member function to this class, without the hassle
of writing something for each existing function of that class.
I can make a new class with a new name, and do not need to add
any field. If have tried the following and it nearly works:
#include<iostream>
using namespace std;
#include<gmpxx.h>
// attempt at a straight extension of gmpxx's mpz_class
class myz_class : public mpz_class {
public:
// smallest n such that 2^^n is greater than absolute value
mp_bitcnt_t bitlen()
This should be 'const'.
{
mp_bitcnt_t n = mpz_sgn(get_mpz_t());
if (n!=0)
n = mpz_sizeinbase(get_mpz_t(), 2);
return n;
};
};
int main (void)
{
mpz_class p;
myz_class y;
p = 0;
// y = 0; // does not compile, error: no match for 'operator='
for (int i=0; i<5; ++i)
{
cout
<< "# p="<< p
<< " abs(p)="<< abs(p)
<< " y="<< y
<< " abs(y)="<< abs(y)
<< " bitlen(y)="<< y.bitlen()
<< "\n";
++p;
++y; // works!
}
return 0;
}
I have two problems:
1) it appears that the overloaded operator = did not make it from
mpz_class to myz_class even though operator ++ did.
The problem is that the compiler automatically generates a copy assignment
operator for you, and it hides the operator= implementation(s) from the base class.
Ah that "copy assignment" gizmo makes = behave differently than ++
See the FAQ about such hiding.
I read<http://www.parashift.com/c++-faq-lite/assignment-operators.html#faq-12.4>
and only vaguely get what happens in the case of my code. Will learn.
That one is relevant yes.
What you're up against, though, is this:
<url: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9>
A simple solution:
using mpz_class::operator=;
I guess that you mean
y mpz_class::operator= 0;
No, I meant what I wrote. Place that in your class definition.
2) short of using a macro, how do I change things in order to
write bitlen(y) much like I write abs(y)?
typedef ptrdiff_t Size;
inline Size bitlen( myz_class const& v )
{
return v.bitlen();
}
At least I fully get that one. Many thanks.
You're welcome.
Cheers & hth.,
- Alf
PS: Kai-Uwe Bux, else-thread, managed to see the Big Picture. I'd follow that
advice! ;-)
--
blog at <url: http://alfps.wordpress.com>