TITLE: Inheritance or templates? RC = Raghavan Chakravarti (rchak@saucer.cc.umr.edu) RB = Russell Blackadar JS = John Max Skaller (maxtal@Physics.usyd.edu.au), 26 Mar 95 RC: I have a type casting doubt. Say i have class A { public: int a; int b; A(int i,int j) { a=i; b=j; } }; class B { public: int a; int b; B(int i,int j) { a=i; b=j; } }; B Bobj; cout << ((A) bObj).a; // gives error cout << ( (A*) (void*) &bObj)->a; // prints 1 correctly JS: [Note its] better style to write A(int i, int j) : a(i), b(j) {} [Prints 1 correctly] ... on some machines. RC: My question why is the first one not allowed ? What is the implication of this ? JS: The kind of cast you are doing is called a "reinterpretation" in which you say to yourself "I know the layout of B is the same as A -- at least for the first few members" and then you tell the compiler that. This is considered to warrant a specific keyword and a new kind of cast: cout << reinterpret_cast(bObj).a; // note use of reference! cout << reinterpret_cast(&bObj).a; Using reinterpret casts is not generally a good idea. RC: Secondly if I have 2 classes which have similar data members is it wise to typecast as done previously ? RB: No. That's what inheritance is for. JS: Not really. Its what templates are for: template void print(T const& object) { cout << object.a << ", " << object.b << endl; } print(aObj); print(bObj); [ I added caps for emphasis below. -adc ] INHERITANCE ISN'T FOR WHEN TWO CLASSES ARE SIMILAR, ITS FOR WHEN THE TYPE OF ONE CLASS _IS_ THE TYPE OF THE OTHER. INHERITANCE IS AN INVASIVE TECHNIQUE TO BE USED WITH CAUTION.