home *** CD-ROM | disk | FTP | other *** search
- //----------------------------------------------------------
- // VIRTUAL.C -
- // (c) 1990 by Thole Groeneveld & toolbox -
- //----------------------------------------------------------
-
- /*
- Dieses Programm demonstriert den virtuellen Aufruf-
- mechanismus in C++.
- Weitere Informationen siehe Ellis & Stroustrup :
- The Annotated C++ Reference Manual, S.227 ff.
- */
-
- #include <stdio.h>
-
- typedef struct TabInfo {
- void (*f)(); // Zeiger auf virtuelle Memberfunktion
- int offset; // Korrekturwert des "this" Zeigers
- } TabInfo; // (nur bei Mehrfachvererbung)
-
- // Eine Basisklasse
- typedef struct base {
- TabInfo *ti; // Zeiger auf "Virtual Function Table"
- int base_info;
- } base;
-
- // class D1 : public base ...
- typedef struct {
- base b;
- int D1_info;
- } D1;
-
- // class D2 : public ... , public base ... (Mult. Inherit.)
- typedef struct {
- double D2_info;
- base b; // base ist nach hinter "verruscht" !
- } D2;
-
- void print_base (base *this) {
- printf ("base.info = %d \n", this -> base_info);
- }
-
- void print_D1 (D1 *this) {
- printf ("base.info = %d \n", this -> b.base_info);
- printf (" D1.info = %d \n", this -> D1_info);
- }
-
- void print_D2 (D2 *this) {
- printf ("base.info = %d \n", this -> b.base_info);
- printf (" D2.info = %lf \n", this -> D2_info);
- }
-
- void f_base (base *this) {
- puts ("Hier ist b1");
- }
-
- void f_D1 (D1 *this) {
- puts ("Hier ist d1");
- }
-
- void f_D2 (D2 *this) {
- puts ("Hier ist d2");
- }
-
- // Virtual Function Tables
- TabInfo base_ti_arr[] = {{print_base, 0}, { f_base, 0 }};
- TabInfo D1_ti_arr[] = {{print_D1, 0}, { f_D1, 0 }};
- TabInfo D2_ti_arr[] = {{print_D2, -sizeof(double)},
- {f_D2, -sizeof(double)}};
-
- // Initialisierung der "Klassen"
- base b1 = { base_ti_arr, 100 };
- D1 d1 = { { D1_ti_arr, 101 }, 123 };
- D2 d2 = { 321.0, { D2_ti_arr, 102 } };
-
- // Für print sind alle übergebenen Zeiger von Typ base*
- void print (base *b) {
- b -> ti[1].f ((char*) b + (b -> ti[1].offset));
- b -> ti[0].f ((char*) b + (b -> ti[0].offset));
- }
-
- void main()
- {
- base *b;
-
- b = &b1;
- print(b);
- b = &d1.b;
- print(b);
- b = &d2.b;
- print(b);
- }
- //----------------------------------------------------------
- // Ende von VIRTUAL.C -