Why doesn't C++ allow adding new methods to classes?

It seems like a rather arbitrary limitation. Aren't regular methods just like C functions with a parameter that points to the instance?

If so I don't see why adding new methods should force me to recompile the rest of my class. Why not allow adding methods via a separate amendment header and a separate amendment implementation.


Consider this example

  // in some header

  struct X
  {
      float func(float);
  };

  // and in another source file

  void caller()
  {
       X x;
       std::cout << x.func(2);     // will call X:func(float)
  }

Now let's say we decide to add a new version of func() that accepts an int.

        // in some header

  struct X
  {
      float func(float);
      void func(int);
  };

  // and in another source file

  void caller()
  {
       X x;
       std::cout << x.func(2);
  }

If the caller() function is not recompiled, there is no way to register that the function it is calling has changed - it will keep calling X::func(float) in the build.

Then - possibly months (or in large systems, years) after the fact - another developer makes a completely unrelated change to one of the functions in the same source file as caller(). Hence that source file gets rebuilt ... finally. Suddenly that person finds that caller() won't compile - with error messages that have nothing whatsoever to do with changes of code he or she is implementing.

All this happens when the offender - the programmer who introduced the new member functions but didn't trigger a recompile and rebuild - is nowhere to be seen.

The developer left behind is left to fix the mess. With no information about what actually caused the problem, why it was working yesterday but not today, no real clue as to how to fix it properly .... but still the one who will be held responsible.

This is just one of many problems that the "arbitrary limitation" in C++ will prevent.


A couple of things comes to my mind. On one hand you need to declare the scope of the method, I presume that's the reason why you are allowed to add new operators in the way that you are suggesting.

On the other hand, you have a problem with inheritance. The compiler need to know all the virtual methods in order to include them in the vtable.