Uploaded image for project: 'Mesos'
  1. Mesos
  2. MESOS-2756

Update style guide: Avoid object slicing

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Accepted
    • Major
    • Resolution: Unresolved
    • None
    • None
    • None
    • 1

    Description

      In order to improve the safety of our code base, let's augment the style guide to:
      "Disallow public construction of base classes"
      so that we can avoid the object slicing problem. This is a good pattern to follow in general as it prevents subtle semantic bugs like the following:

      ObjectSlicing.cpp
      #include <stdio.h>
      #include <vector>
      
      class Base {
        public:
        Base(int _v) : v(_v) {}
        virtual int get() const { return v; }
        protected:
        int v;
      };
      
      class Derived : public Base {
        public:
        Derived(int _v) : Base(_v) {}
        virtual int get() const { return v + 1; }
      };
      
      int main() {
        Base b(5);
        Derived d(5);
        std::vector<Base> vec;
        vec.push_back(b);
        vec.push_back(d);
        for (const auto& v : vec) {
          printf("[%d]\n", v.get());
        }
      }
      

      Attachments

        Activity

          People

            jvanremoortere Joris Van Remoortere
            jvanremoortere Joris Van Remoortere
            Benjamin Hindman Benjamin Hindman
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated: