#include <iostream> using namespace std; template <typename e1, typename e2> class mix : public e1, public e2 { public: mix() : e1(1), e2(2) { // set nothing here cerr << "this " << << " in mix" << endl; print(cerr); } void print(ostream& os) { os << "e1: " << e1::e1 << ", e2: " << e2::e2 << endl; // os << "e1: " << e1 << ", e2: " << e2 << endl; won't compile } }; class element1 { public: element1(unsigned int e) : e1(e) { cerr << "this " << << " in element1" << endl; } unsigned int e1; }; class element2 { public: element2(unsigned int e) : e2(e) { cerr << "this " << << " in element2" << endl; } unsigned int e2; }; int main(int argc, char** argv) { mix<element1, element2> m; }
now, since we're equally inheriting 2 template parameter classes, expect this
same in 2 constructors, not case. here run log:
this 0x7fff6c04aa70 in element1 0x7fff6c04aa74 in element2 0x7fff6c04aa70 in mix e1: 1, e2: 2
as can see, while this
same in element1 , mix, not true element2. why that? also, expect have access e1 , e2 base classes. can explain behavior?
the element mix
contains element1
, element2
. these - perhaps implementation aligned - written after 1 in memory. if use mix
element1
, point first of 2 (with size of element1
), if use element2
point second (with size of element2
) , if use mix
point base address, same element1
s base address, has differenz size (at least size of element1
+ size of element2
).
edit: can verify outputting size too:
#include
using namespace std; template <typename e1, typename e2> class mix : public e1, public e2 { public: mix() : e1(1), e2(2) { // set nothing here cerr << "this " << << " + " << sizeof(*this) << " in mix" << endl; print(cerr); } void print(ostream& os) { os << "e1: " << e1::e1 << ", e2: " << e2::e2 << endl; // os << "e1: " << e1 << ", e2: " << e2 << endl; won't compile } }; class element1 { public: element1(unsigned int e) : e1(e) { cerr << "this " << << " + " << sizeof(*this) << " in element1" << endl; } unsigned int e1; }; class element2 { public: element2(unsigned int e) : e2(e) { cerr << "this " << << " + " << sizeof(*this) << " in element2" << endl; } unsigned int e2; }; int main(int argc, char** argv) { mix<element1, element2> m; }
output:
this 0x7fffc9cad310 + 4 in element1 0x7fffc9cad314 + 4 in element2 0x7fffc9cad310 + 8 in mix e1: 1, e2: 2
Comments
Post a Comment