Is there a way not to have to _write_ the derived ctors that _just_ forwards
to the base ctor ?
regards,
No. Constructors are not inherited.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
I would do:
#include <iostream>
using namespace std;
class B {
public:
int val;
B(int specific):val(specific){};
};
class D : public B {
public:
D():B(42){}
};
class D1 : public D {
};
class D2 : public D {
};
int main(){
D1 d1;
D2* d2=new D2();
cout<<d1.val<<" "<<d2->val<<endl;
return(0);
}
/*
-*- mode: compilation; default-directory: "~/src/tests-c++/" -*-
Compilation started at Fri Jan 30 15:41:24
SRC="/home/pjb/src/tests-c++/ctor.c++" ; EXE="ctor" ; g++ -g3 -ggdb3 -o ${EXE} ${SRC} && ./${EXE} && echo status = $?
42 42
status = 0
Compilation finished at Fri Jan 30 15:41:25
*/
--
__Pascal Bourguignon__
By the same token, B could be a template:
template<int initialiser> class B {
protected:
B(int param = initialiser) : b(param) {}
public:
int b;
};
class D1 : public B<42> {};
class D2 : public B<666> {};
#include <iostream>
#include <ostream>
int main() {
D1 d1;
D2 d2;
std::cout << d1.b << std::endl;
std::cout << d2.b << std::endl;
}
Or you could even give the 'initialiser' template argument some default
value and not define it for those who should have the default:
template<int initialiser = 42> class B {
protected:
B(int param = initialiser) : b(param) {}
public:
int b;
};
class D1 : public B<> {};
class D2 : public B<666> {};
class D3 : public B<> {};
#include <iostream>
#include <ostream>
int main() {
D1 d1;
D2 d2;
D3 d3;
std::cout << d1.b << std::endl;
std::cout << d2.b << std::endl;
std::cout << d3.b << std::endl;
}
The problem, however, is that you still need to spell out the template
argument or rely on some default. You either do it in the constructor
of each Dx class or do it using your scheme or the template.
Another problem is that D1, D2 and D3 above all derive from different
base classes.
All? No, only two of them. D1 and D3 derive from the same type.
Not in the current C++ standard, but the next standard will have a
syntax to do exactly that.
http://en.wikipedia.org/wiki/C%2B%2B0x#Object_construction_improvement