This is an interview question, the interview has been done.
What things can make C++ slower than C ?
The interviewer asked it very deep and always asked “anything else ? ” whenever I said something.
My ideas:
C++ features not available in C may have some cost.
For example, if we use assignment to initialize class’s members inside a constructor not by the initialization list, the member’s default constructor may be called once before the body of the constructor, and then that value wiped out by the assignment.
Virtual functions need to be called by searching virtual function pointer. This is a overhead.
Any better ideas ?
Any help will be appreciated.
thanks !!!
Nothing. In fact, C++ is faster than C. Ever compared
std::sorttoqsort?People say that virtual functions cost time to call. They do. But so does the C equivalent of looking up in a vtable. If you write equivalent logic in both languages, the C++ version will be more maintainable, cleaner, and faster.
Edit: Oh yeah, you can call
printffrom C++ if you want, or completely re-do the stream implementation if you want.And did I mention that the performance of a program which crashes due to a misplaced NULL terminator is fairly immaterial?
Macros and inline functions will “bloat” a C executable just as surely as templates will in C++.