SlideShare a Scribd company logo
1 of 23
Download to read offline
Multiple Inheritance for C+ +


                  By
           Bjarne Stroustrup
            AT & T Bell Labs
            Murray Hill, NJ




          Click to edit Date
 Presented by Balachandran Natarajan
Balachandran Natarajan                                  Multiple Inheritance for C++

          M o tivation for Multiple Inheritance
     PS_Coordinat              PS_Point
                                                             UG_Display
       e                       {
                                                             {
     {                         <List of ops>
                                                             <List of ops>
     <List of ops>             PS_Coordinate pt_;
                                                             UG_Color color_;
     double x_;                };
                                                             UG_Layer layer_;
     …
                                                             UG_Width width_;
     };                         P S _ S p l i n e {..};      };
                                PS_Bspline {…};
PS_Line
                                P S _ B c u r v e {..};   U G _ A d D i s p l a y {..
{
                                                              };
<List of ops>
                                        •   PS_* and UG_* are from different modules
PS_Coordinate start_;
                                        •   The display properties are added to the
PS_Coordinate end_;                         CAD geometry for visualization and
};                                          translation
                                        •   Geometry used for operations like CAM,
                                            FEA etc.
    Washington University, St. Louis
Balachandran Natarajan                          Multiple Inheritance for C++

                                   G o als

                                        •    A brief history of MI in C++
                                        •    Myths, the need for this
                                             presentation.
                                        •    H o w M I is to be
                                             implemented for different
                                             use cases
                                        •    Controversies that
                                             surrounded MI – follows
                                             from the Myths
                                        •    Actual overheads and
                                             conclusion




Washington University, St. Louis
Balachandran Natarajan                 Multiple Inheritance for C++

                        Multiple Inheritance
 • Representation of various widgets in a windowing
   system.
 • Representation of various processors and
   architectures for a multi- machine. Multi-environ m e nt
   debugger
 • Allows combination of independent concepts into a
   composite concept.
 • N concepts can be married to M concepts in N+ M
   ways using MI
      – To achieve the same thing we need N+M+N*M classes
        with duplication.



Washington University, St. Louis
Balachandran Natarajan                                   Multiple Inheritance for C++

                                   S o m e History
                                        •   Made its appearance in Release 2.0 of
                                            Cfront
                                        •   Bjarne considers having MI in Release
                                            2.0 was a mistake
                                             – Not as important as parameterized
                                               types and exception handling
                                        •   Reasons for implementing in 2.0
                                             – Fitted very well in to C++ type
                                               system
                                             – C o u l d b e i m p l e m e n t e d w i t h i n Cfront
                                             – Considered to be difficult to
                                               implement
                                                   • Brad Cox says impossible




Washington University, St. Louis
Balachandran Natarajan                            Multiple Inheritance for C++

                                   S o m e History
                                           •   Solution conceived in
                                               1984 with Stein Krogdal
                                               of S i m u l a


                                           •   Solution similar to Ole-
                                               Johan Dahl considered in
                                               1966.


                                           •   Solution rejected because
                                               it would have complicated
                                               the GC.


                                           •   BS later mentions
                                               “Fashion affected the
                                               sequence of events”


Washington University, St. Louis
Balachandran Natarajan                        Multiple Inheritance for C++

                                   Myths
                                      •   Complicates Programming
                                          Language significantly


                                      •   Is hard to implement


                                      •   Expensive to run




                                      •   Are the above really true?




Washington University, St. Louis
Balachandran Natarajan                       Multiple Inheritance for C++

                              C + + Object Model
class 2dpoint {
                                        float y
float x, y;                                           •   Static data
int translate (const 2dpoint            float x           members outside
    *);                                                   the class
};                                                    •   Static and non static
2dpoint *pt;
                                                          function members
pt->translate (…);=è f__F12dpoint (pt,…)                  outside the class
                                                          object
                                                      •   N o n - static data
•Based on the Simple Model
                                                          members within the
•Optimized for time and space overhead.                   object
•Table driven model is not efficient



     Washington University, St. Louis
Balachandran Natarajan                          Multiple Inheritance for C++

  O b j e c t Model with Single Inheritance

  class 3dpoint: 2dpoint {                    float z
  float z;
  int translate (const 3dpoint                float y
      *);
                                              float x
  };

    3dpoint *pt;
    pt->translate (3dpoint *);=è f__F23dpoint (pt, 3dpoint *)

    3dpoint *pt;
    pt->translate (2dpoint *);=è f__F13dpoint (pt, 2doint *);




Washington University, St. Louis
Balachandran Natarajan                       Multiple Inheritance for C++

       Inheritance with Virtual functions
  class A { float a; virtual void
     f (float);
                                                         float a
  virtual void g (float);            Object
  virtual void h (float);           Layout for           float b
  };
                                    Object of            float c
  class B : A {float b; void f
     (float);};                      type C
                                                         __vptr
  class C: B {float c; void g
     (float);};                        type_info
                                        C::g ()
C *pg;
Pg->g (2.0); è                          B::f ()
(*(pg->__vptr[0])) (pg, 2.0)
                                        A::h ()
 Washington University, St. Louis
Balachandran Natarajan                             Multiple Inheritance for C++

                    Multiple Inheritance – Si m ple
                                                                               pf
class A { ..};                         C *pf;             A Part
class B {..};                          pf->bf ();         B Part
class C:A, B {};
                                                         C Part            B::bf
•   C is a A & a B
                                                                           defined
•   The declaration
                                                                           from here
class C:B, A {};
                                                       delta B
is equivalent to above
•   Assume A has a
    m e t h o d af () and B                f__f1B(B*)((char*pf+delta B))
    has a method bf ()


      For ambiguities in this case see section 4.3 of the paper

    Washington University, St. Louis
Balachandran Natarajan                       Multiple Inheritance for C++

                        Interesting Use Cases
 •   Casting                       •    Comparisons
 C* pc;                            pc == pb;
 B* pb;                            /* pc ==(C*)pb or
                                      equivalently (B*)pc == pb
 pb=(B*)pc;                           which
 /*pb                                 is,(B*)((char*)pc+delta(B)
    =(B*)((char*)pc+delta(B)          ) == pb or equivalently pc
    ) */                              == (C*)((char*)pb-
                                      delta(B))
 pb=pc;                             */
 /*pb =                            •    Zero Valued pointers
    (B*)((char*)pc+delta(B))       C* pc = 0;
    */
                                   B* pb = 0;
 pc=pb;                            if (pb == 0) ...
 // error: cast needed             pb = pc; // pb =
 pc=(C*)pb;                           (B*)((char*)pc+delta(B))
 /*pc = (C*)((char*)pb-            if (pb == 0) ..
    delta(B))*/                    So use pb = (pc ==0)?0:
                                      (B*)((char*)pc+delta(B))


Washington University, St. Louis
Balachandran Natarajan                          Multiple Inheritance for C++

                        M I – with Virtual functions
class A {virtual void f ()};            A Part            struct vtbl_entry {
class B {                                                 void *(fct) (); int delta;};
                                        B Part
virtual void f ();                                           C::f () -delta B
virtual void g ();
                                        __vptr
                                        C Part               B::g () 0
};
class C:A, B {void f ();};              __vptr               C::f ()       0
                                                             B::g () delta B
                  B *pf = new C;
                  pf->f (); // Should call C::f ()


       For ambiguities in this case see section 5.2 of the paper

     Washington University, St. Louis
Balachandran Natarajan                     Multiple Inheritance for C++

                            Multiple Inclusions
 • A class can have any number of base classes like
 class C:A, B, D, E, F {..};
 • Illegal to specify a class name twice in the list
 class C:A, B,B, F {..}; //illegal
 • A m a y b e included more than once as a base class
 class L {..}; class A:L {..}; class B:L
   {..}; C:A,B {..};
 • For scope resolution and type checking please see
   sec. 6.2 and 6.3 in paper.




Washington University, St. Louis
Balachandran Natarajan                Multiple Inheritance for C++

                 MI with Virtual Base Classes
 • Independent MI
 • One Object of the base class in the final derived
   class, irrespective of the number of times derived.
 • Base classes can be declared virtual to achieve the
   above like this
 class AW: virtual W {...};
 class BW: virtual W {...};
 class CW:AW,BW{};
 • W shared between AW and BW
 • Except for the unique object, this is just similar to the
   n o n - unique case.


Washington University, St. Louis
Balachandran Natarajan                               Multiple Inheritance for C++

             Object Model with Virtual Base Class
                                 ptr to w                               ptr to w
ptr to aw                                   ptr to cw
                AW Part                                 AW Part

                W Part
                                                        BW Part
      •     Casting allowed from the
                                                        CW Part
            derived class to the base
            class but not vice- versa
                                                         W Part
      •     The latter requires a “back-
            pointer” and unsuitable
            C++.
      •     Use virtual functions instead
            J
     Washington University, St. Louis
Balachandran Natarajan                       Multiple Inheritance for C++

                                 Virtual Functions
 class W {                                                        ptr to w
 virtual void           d (BW) –
                BW::f                            AW Part
    f();                d (W)
 virtual void AW::g     -d (W)
    g();        CW::h   -d (W)
 virtual void W::k        0                      BW Part
    h();
class AW: void
 virtual virtual W {void g();};                   CW Part
    k();
class BW: virtual W {void f();};                vptr
 };
class CW: AW ,BW {void h();};
CW* pcw = new CW;                                 W Part
pcw->f(); // BW::f()
pcw->g(); // AW::g()                       Ambiguities detected at
pcw->h(); // CW::h()                       vtbl construction time
((AW*)pcw)->f(); // BW::f();


   Washington University, St. Louis
Balachandran Natarajan                        Multiple Inheritance for C++

                                   Virtual Bases
 • Method combination, not supported in C++
      – Call and return a solution to mimic :before () and :after
        ()
 • Method combination can be achieved using manually
      – Problem is to avoid multiple calls to the same function
        in the virtual class
      – See 7.3 of the paper for a good example
 • Constructors and Destructors
      – Ctor for base classes are called before Ctor for derived
        classes
      – Dtors are reverse
      – Ctors are called as they appear in the list but the
        virtual base is constructed first.


Washington University, St. Louis
Balachandran Natarajan                             Multiple Inheritance for C++

                                   C o n troversies
                                             •   Tom Cargill, 1991, First
                                                 C++ Conference, Santa Fe
                                             •   Jim Waldo, 1993
                                             •   Smalltalk doesn’t
                                                 implement MI
                                             •   BS first implementation
                                                 had additional overhead.
                                             •   BS focused on
                                                 implementation.
                                             •   Too hard to use, poor
                                                 design an buggy code
                                             •   Delegation is an
                                                 alternative
                                             •   Makes GC and tools
                                                 difficult.


Washington University, St. Louis
Balachandran Natarajan                      Multiple Inheritance for C++

                 Alternative Object Layout for MI
    class A {virtual void f ()};
    class B {                               A Part
    virtual void f ();                      B Part
    virtual void g ();                      __vptr
    };                                                           B::g
                                            C Part
    class C:A, B {void f ();};
                                            __vptr              C::f ()    0
•   Compact virtual function tables
•   Faster calls to virtual functions if
                                                     this -= delta (B)
    delta is 0
                                                        goto c::f
     •    Delta is 0 for SI
•   Less portable
•   ‘goto’ is not supported on m/c
    architectures


         Washington University, St. Louis
Balachandran Natarajan                              Multiple Inheritance for C++

                                   D e l e g a tion
 •   Presented at EUUG in May 1987
 •   Class specified like this                       B *p
                                                                   int b
 class B {int b; void                                int c
   f();};
 class C: *p {B*p; int c;} • Very promising as delegation
                                                could be used to reconfigure
 •   The :*p meant that something
                                                object at run-ti m e
     like this
                                            •   Implementation trivial, run- ti m e
 void f (C* q)
                                                space efficiency ideal
 {
                                            •   Bugs and confusion, removed
    q->f ();                                    from Release 2.0
   //meaning q->p->f();                          • Functions in delegating
 }                                                 class do not override
                                                 • Delegated fn. cannot call
                                                   delegating fn,

Washington University, St. Louis
Balachandran Natarajan                     Multiple Inheritance for C++

                                   Overheads
 • One operation with a constant for each use of a member in
   a base class.
      – Only with MI
 • One word per function in each vtbl (to hold the delta).
      – Normal use case
 • One memory reference and one operation for each call of a
   virtual function.
      – Normal use case
 • One memory reference and one operation for access of a
   base class member of a virtual base class.
      – Only with MI


Washington University, St. Louis
Balachandran Natarajan                              Multiple Inheritance for C++

                                   C o n clusions
 •   What makes a language facility      •   Ambiguities are illegal.
     hard to use?                        •   Rules for use of members are
      – Lots of rules.                       what they were for single
      – Subtle differences between           inheritance.
         rules.                          •   Visibility rules are what they were
      – Inability to automatically           for single inheritance.
         detect common errors.           •   Initialization rules are what they
      – Lack of generality.                  were for single inheritance.
      – Deficiencies.                    •   Violations of these rules are
                                             detected by the compiler.
                                         •   Easier to implement
                                         •   Portability is not affected




Washington University, St. Louis

More Related Content

Viewers also liked

Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programmingAbzetdin Adamov
 
Mendelian inheretence part 1
Mendelian inheretence part 1 Mendelian inheretence part 1
Mendelian inheretence part 1 mohamed abdukadir
 
Notes incomplete codominance
Notes incomplete codominanceNotes incomplete codominance
Notes incomplete codominancestewart_j
 
QUALITATIVE AND QUANTITATIVE CHARACTERS OF THREE COMMON CARP (Cyprinus carpio...
QUALITATIVE AND QUANTITATIVE CHARACTERS OF THREE COMMON CARP (Cyprinus carpio...QUALITATIVE AND QUANTITATIVE CHARACTERS OF THREE COMMON CARP (Cyprinus carpio...
QUALITATIVE AND QUANTITATIVE CHARACTERS OF THREE COMMON CARP (Cyprinus carpio...Repository Ipb
 
Outbound Training
Outbound TrainingOutbound Training
Outbound Trainingpavansriram
 
Extension of mendelian inheritance
Extension of mendelian inheritanceExtension of mendelian inheritance
Extension of mendelian inheritanceOmar Jacalne
 
C++ Multiple Inheritance
C++ Multiple InheritanceC++ Multiple Inheritance
C++ Multiple Inheritanceharshaltambe
 
2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and PointersMichael Heron
 
Mendel concept of genetics
Mendel concept of geneticsMendel concept of genetics
Mendel concept of geneticsvarsha jain
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsMarlom46
 
How To Use VLC.pdf
How To Use VLC.pdfHow To Use VLC.pdf
How To Use VLC.pdfnoniefer20
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
Cell structure and functions
Cell structure and functionsCell structure and functions
Cell structure and functionsJoy Batang Ü
 
Pedigree analysis
Pedigree analysisPedigree analysis
Pedigree analysissikojp
 
Some Basic Concepts of Object Oriented Methodology
Some Basic Concepts of Object Oriented MethodologySome Basic Concepts of Object Oriented Methodology
Some Basic Concepts of Object Oriented MethodologyManoj Kumar
 
Friend functions
Friend functions Friend functions
Friend functions Megha Singh
 
Object oriented methodology & unified modeling language
Object oriented methodology & unified modeling languageObject oriented methodology & unified modeling language
Object oriented methodology & unified modeling languageIsmail El Gayar
 

Viewers also liked (20)

Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
 
Mendelian inheretence part 1
Mendelian inheretence part 1 Mendelian inheretence part 1
Mendelian inheretence part 1
 
Notes incomplete codominance
Notes incomplete codominanceNotes incomplete codominance
Notes incomplete codominance
 
QUALITATIVE AND QUANTITATIVE CHARACTERS OF THREE COMMON CARP (Cyprinus carpio...
QUALITATIVE AND QUANTITATIVE CHARACTERS OF THREE COMMON CARP (Cyprinus carpio...QUALITATIVE AND QUANTITATIVE CHARACTERS OF THREE COMMON CARP (Cyprinus carpio...
QUALITATIVE AND QUANTITATIVE CHARACTERS OF THREE COMMON CARP (Cyprinus carpio...
 
Outbound Training
Outbound TrainingOutbound Training
Outbound Training
 
Extension of mendelian inheritance
Extension of mendelian inheritanceExtension of mendelian inheritance
Extension of mendelian inheritance
 
C++ Multiple Inheritance
C++ Multiple InheritanceC++ Multiple Inheritance
C++ Multiple Inheritance
 
2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers
 
Mendel concept of genetics
Mendel concept of geneticsMendel concept of genetics
Mendel concept of genetics
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
How To Use VLC.pdf
How To Use VLC.pdfHow To Use VLC.pdf
How To Use VLC.pdf
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Cell structure and functions
Cell structure and functionsCell structure and functions
Cell structure and functions
 
Medels laws
Medels lawsMedels laws
Medels laws
 
Pedigree analysis
Pedigree analysisPedigree analysis
Pedigree analysis
 
Some Basic Concepts of Object Oriented Methodology
Some Basic Concepts of Object Oriented MethodologySome Basic Concepts of Object Oriented Methodology
Some Basic Concepts of Object Oriented Methodology
 
Heredity
HeredityHeredity
Heredity
 
Friend functions
Friend functions Friend functions
Friend functions
 
Data flow diagrams - DFD
Data flow diagrams - DFDData flow diagrams - DFD
Data flow diagrams - DFD
 
Object oriented methodology & unified modeling language
Object oriented methodology & unified modeling languageObject oriented methodology & unified modeling language
Object oriented methodology & unified modeling language
 

More from elliando dias

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slideselliando dias
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScriptelliando dias
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structureselliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de containerelliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Librarieselliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Webelliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduinoelliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorceryelliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Designelliando dias
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makeselliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebookelliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Studyelliando dias
 

More from elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
 
Ragel talk
Ragel talkRagel talk
Ragel talk
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
 
Rango
RangoRango
Rango
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
 

Multiple Inheritance For C++

  • 1. Multiple Inheritance for C+ + By Bjarne Stroustrup AT & T Bell Labs Murray Hill, NJ Click to edit Date Presented by Balachandran Natarajan
  • 2. Balachandran Natarajan Multiple Inheritance for C++ M o tivation for Multiple Inheritance PS_Coordinat PS_Point UG_Display e { { { <List of ops> <List of ops> <List of ops> PS_Coordinate pt_; UG_Color color_; double x_; }; UG_Layer layer_; … UG_Width width_; }; P S _ S p l i n e {..}; }; PS_Bspline {…}; PS_Line P S _ B c u r v e {..}; U G _ A d D i s p l a y {.. { }; <List of ops> • PS_* and UG_* are from different modules PS_Coordinate start_; • The display properties are added to the PS_Coordinate end_; CAD geometry for visualization and }; translation • Geometry used for operations like CAM, FEA etc. Washington University, St. Louis
  • 3. Balachandran Natarajan Multiple Inheritance for C++ G o als • A brief history of MI in C++ • Myths, the need for this presentation. • H o w M I is to be implemented for different use cases • Controversies that surrounded MI – follows from the Myths • Actual overheads and conclusion Washington University, St. Louis
  • 4. Balachandran Natarajan Multiple Inheritance for C++ Multiple Inheritance • Representation of various widgets in a windowing system. • Representation of various processors and architectures for a multi- machine. Multi-environ m e nt debugger • Allows combination of independent concepts into a composite concept. • N concepts can be married to M concepts in N+ M ways using MI – To achieve the same thing we need N+M+N*M classes with duplication. Washington University, St. Louis
  • 5. Balachandran Natarajan Multiple Inheritance for C++ S o m e History • Made its appearance in Release 2.0 of Cfront • Bjarne considers having MI in Release 2.0 was a mistake – Not as important as parameterized types and exception handling • Reasons for implementing in 2.0 – Fitted very well in to C++ type system – C o u l d b e i m p l e m e n t e d w i t h i n Cfront – Considered to be difficult to implement • Brad Cox says impossible Washington University, St. Louis
  • 6. Balachandran Natarajan Multiple Inheritance for C++ S o m e History • Solution conceived in 1984 with Stein Krogdal of S i m u l a • Solution similar to Ole- Johan Dahl considered in 1966. • Solution rejected because it would have complicated the GC. • BS later mentions “Fashion affected the sequence of events” Washington University, St. Louis
  • 7. Balachandran Natarajan Multiple Inheritance for C++ Myths • Complicates Programming Language significantly • Is hard to implement • Expensive to run • Are the above really true? Washington University, St. Louis
  • 8. Balachandran Natarajan Multiple Inheritance for C++ C + + Object Model class 2dpoint { float y float x, y; • Static data int translate (const 2dpoint float x members outside *); the class }; • Static and non static 2dpoint *pt; function members pt->translate (…);=è f__F12dpoint (pt,…) outside the class object • N o n - static data •Based on the Simple Model members within the •Optimized for time and space overhead. object •Table driven model is not efficient Washington University, St. Louis
  • 9. Balachandran Natarajan Multiple Inheritance for C++ O b j e c t Model with Single Inheritance class 3dpoint: 2dpoint { float z float z; int translate (const 3dpoint float y *); float x }; 3dpoint *pt; pt->translate (3dpoint *);=è f__F23dpoint (pt, 3dpoint *) 3dpoint *pt; pt->translate (2dpoint *);=è f__F13dpoint (pt, 2doint *); Washington University, St. Louis
  • 10. Balachandran Natarajan Multiple Inheritance for C++ Inheritance with Virtual functions class A { float a; virtual void f (float); float a virtual void g (float); Object virtual void h (float); Layout for float b }; Object of float c class B : A {float b; void f (float);}; type C __vptr class C: B {float c; void g (float);}; type_info C::g () C *pg; Pg->g (2.0); è B::f () (*(pg->__vptr[0])) (pg, 2.0) A::h () Washington University, St. Louis
  • 11. Balachandran Natarajan Multiple Inheritance for C++ Multiple Inheritance – Si m ple pf class A { ..}; C *pf; A Part class B {..}; pf->bf (); B Part class C:A, B {}; C Part B::bf • C is a A & a B defined • The declaration from here class C:B, A {}; delta B is equivalent to above • Assume A has a m e t h o d af () and B f__f1B(B*)((char*pf+delta B)) has a method bf () For ambiguities in this case see section 4.3 of the paper Washington University, St. Louis
  • 12. Balachandran Natarajan Multiple Inheritance for C++ Interesting Use Cases • Casting • Comparisons C* pc; pc == pb; B* pb; /* pc ==(C*)pb or equivalently (B*)pc == pb pb=(B*)pc; which /*pb is,(B*)((char*)pc+delta(B) =(B*)((char*)pc+delta(B) ) == pb or equivalently pc ) */ == (C*)((char*)pb- delta(B)) pb=pc; */ /*pb = • Zero Valued pointers (B*)((char*)pc+delta(B)) C* pc = 0; */ B* pb = 0; pc=pb; if (pb == 0) ... // error: cast needed pb = pc; // pb = pc=(C*)pb; (B*)((char*)pc+delta(B)) /*pc = (C*)((char*)pb- if (pb == 0) .. delta(B))*/ So use pb = (pc ==0)?0: (B*)((char*)pc+delta(B)) Washington University, St. Louis
  • 13. Balachandran Natarajan Multiple Inheritance for C++ M I – with Virtual functions class A {virtual void f ()}; A Part struct vtbl_entry { class B { void *(fct) (); int delta;}; B Part virtual void f (); C::f () -delta B virtual void g (); __vptr C Part B::g () 0 }; class C:A, B {void f ();}; __vptr C::f () 0 B::g () delta B B *pf = new C; pf->f (); // Should call C::f () For ambiguities in this case see section 5.2 of the paper Washington University, St. Louis
  • 14. Balachandran Natarajan Multiple Inheritance for C++ Multiple Inclusions • A class can have any number of base classes like class C:A, B, D, E, F {..}; • Illegal to specify a class name twice in the list class C:A, B,B, F {..}; //illegal • A m a y b e included more than once as a base class class L {..}; class A:L {..}; class B:L {..}; C:A,B {..}; • For scope resolution and type checking please see sec. 6.2 and 6.3 in paper. Washington University, St. Louis
  • 15. Balachandran Natarajan Multiple Inheritance for C++ MI with Virtual Base Classes • Independent MI • One Object of the base class in the final derived class, irrespective of the number of times derived. • Base classes can be declared virtual to achieve the above like this class AW: virtual W {...}; class BW: virtual W {...}; class CW:AW,BW{}; • W shared between AW and BW • Except for the unique object, this is just similar to the n o n - unique case. Washington University, St. Louis
  • 16. Balachandran Natarajan Multiple Inheritance for C++ Object Model with Virtual Base Class ptr to w ptr to w ptr to aw ptr to cw AW Part AW Part W Part BW Part • Casting allowed from the CW Part derived class to the base class but not vice- versa W Part • The latter requires a “back- pointer” and unsuitable C++. • Use virtual functions instead J Washington University, St. Louis
  • 17. Balachandran Natarajan Multiple Inheritance for C++ Virtual Functions class W { ptr to w virtual void d (BW) – BW::f AW Part f(); d (W) virtual void AW::g -d (W) g(); CW::h -d (W) virtual void W::k 0 BW Part h(); class AW: void virtual virtual W {void g();}; CW Part k(); class BW: virtual W {void f();}; vptr }; class CW: AW ,BW {void h();}; CW* pcw = new CW; W Part pcw->f(); // BW::f() pcw->g(); // AW::g() Ambiguities detected at pcw->h(); // CW::h() vtbl construction time ((AW*)pcw)->f(); // BW::f(); Washington University, St. Louis
  • 18. Balachandran Natarajan Multiple Inheritance for C++ Virtual Bases • Method combination, not supported in C++ – Call and return a solution to mimic :before () and :after () • Method combination can be achieved using manually – Problem is to avoid multiple calls to the same function in the virtual class – See 7.3 of the paper for a good example • Constructors and Destructors – Ctor for base classes are called before Ctor for derived classes – Dtors are reverse – Ctors are called as they appear in the list but the virtual base is constructed first. Washington University, St. Louis
  • 19. Balachandran Natarajan Multiple Inheritance for C++ C o n troversies • Tom Cargill, 1991, First C++ Conference, Santa Fe • Jim Waldo, 1993 • Smalltalk doesn’t implement MI • BS first implementation had additional overhead. • BS focused on implementation. • Too hard to use, poor design an buggy code • Delegation is an alternative • Makes GC and tools difficult. Washington University, St. Louis
  • 20. Balachandran Natarajan Multiple Inheritance for C++ Alternative Object Layout for MI class A {virtual void f ()}; class B { A Part virtual void f (); B Part virtual void g (); __vptr }; B::g C Part class C:A, B {void f ();}; __vptr C::f () 0 • Compact virtual function tables • Faster calls to virtual functions if this -= delta (B) delta is 0 goto c::f • Delta is 0 for SI • Less portable • ‘goto’ is not supported on m/c architectures Washington University, St. Louis
  • 21. Balachandran Natarajan Multiple Inheritance for C++ D e l e g a tion • Presented at EUUG in May 1987 • Class specified like this B *p int b class B {int b; void int c f();}; class C: *p {B*p; int c;} • Very promising as delegation could be used to reconfigure • The :*p meant that something object at run-ti m e like this • Implementation trivial, run- ti m e void f (C* q) space efficiency ideal { • Bugs and confusion, removed q->f (); from Release 2.0 //meaning q->p->f(); • Functions in delegating } class do not override • Delegated fn. cannot call delegating fn, Washington University, St. Louis
  • 22. Balachandran Natarajan Multiple Inheritance for C++ Overheads • One operation with a constant for each use of a member in a base class. – Only with MI • One word per function in each vtbl (to hold the delta). – Normal use case • One memory reference and one operation for each call of a virtual function. – Normal use case • One memory reference and one operation for access of a base class member of a virtual base class. – Only with MI Washington University, St. Louis
  • 23. Balachandran Natarajan Multiple Inheritance for C++ C o n clusions • What makes a language facility • Ambiguities are illegal. hard to use? • Rules for use of members are – Lots of rules. what they were for single – Subtle differences between inheritance. rules. • Visibility rules are what they were – Inability to automatically for single inheritance. detect common errors. • Initialization rules are what they – Lack of generality. were for single inheritance. – Deficiencies. • Violations of these rules are detected by the compiler. • Easier to implement • Portability is not affected Washington University, St. Louis