Peng Yu wrote:
> Hi,
>
> I want B has all the constructors that A has. Obviously, the code
> below would not work. I could define a corresponding B's constructor
> for each A's constructor. But if A has many constructors, it would be
> inconvenient. I'm wondering if there is any way to inherent all A's
> constructor implicitly.
There is no way to inherit constructors. One reason is that a derived class
may add more data members, which would need initialization.
> class A{
> public:
> A(int x) : _x(x) { }
> private:
> int _x;
> };
>
> class B : public A { };
That said, you can forward constructors using templates. E.g., the following
adds a virtual destructor:
template < typename T >
class virtual_destructor : public T {
public:
virtual_destructor ( void ) :
T ()
{}
template < typename A >
virtual_destructor ( A a ) :
T ( a )
{}
template < typename A, typename B >
virtual_destructor ( A a, B b ) :
T ( a, b )
{}
template < typename A, typename B, typename C >
virtual_destructor ( A a, B b, C c ) :
T ( a, b, c )
{}
template < typename A, typename B, typename C,
typename D >
virtual_destructor ( A a, B b, C c, D d ) :
T ( a, b, c, d )
{}
template < typename A, typename B, typename C,
typename D, typename E >
virtual_destructor ( A a, B b, C c, D d, E e ) :
T ( a, b, c, d, e )
{}
template < typename A, typename B, typename C,
typename D, typename E, typename F >
virtual_destructor ( A a, B b, C c, D d, E e, F f ) :
T ( a, b, c, d, e, f )
{}
virtual ~virtual_destructor ( void ) {}
}; // virtual_destructor<T>
This requires some knowledge/guess about the maximum number of arguments in
a constructor. Also, it does not handle reference parameters in
constructors nicely.
It is quite possible that this becomes simpler with variadic templates in
the next standard.
Best
Kai-Uwe Bux