The Weirdness of C++

I’ve been dredging up my C++ for a class recently, and I’m struck by just how weird it feels now that I spend most of my time with Ruby.

I was all proud of myself for remembering how to write a copy constructor. Then I ran into a situation like this:

MyClass a = foo;
MyClass c;
c = foo;

The first line was fine; the last segfaulted. What the heck?

I had hit upon the subtle difference between assignment at construction time and normal assignment. The former calls the copy constructor, the latter calls operator=.

MyClass a = foo;  // calls copy constructor MyClass(foo)
MyClass c;
c = foo;  // calls operator=

I had neglected to provide an operator= for MyClass, so the compiler invented one for me. Since MyClass contained pointers to other structures, that naturally led to problems pretty quickly.

Had I not known to look up the specific behavior of operator=, and then implement a correct one for MyClass, I would have been really confused. This sort of subtlety is what makes me think of C++ as a “hard” language and Ruby as an “easy” language.

To be sure, Ruby has its subtle quirks too, but they occur less frequently and usually around “advanced” topics like metaprogramming. In C++, even a fundamental operation like assignment can have strange, unpredictable properties.

One Reply to “The Weirdness of C++”

  1. There is nothing at all strange or unpredictable about assignment in this case. If anything is strange, it’s that copy constructor invocation and assignment operator invocation look similar. However, it’s not all that surprising either. In the first case, an object is being constructed. In the second case, it’s not.

    C++ creates four methods for you automatically in any empty class. Any class with bare pointers should probably have its own implementation for all four.

Comments are closed.