C++ for Embedded · Interview question

Does adding methods to a class make objects bigger?

A strong answer

No. A non-static, non-virtual method is just a function that takes a hidden this pointer to the object, the code lives once in the .text section, not per object. sizeof an object is the sum of its data members (plus padding), regardless of how many methods the class has. So obj.method() compiles to passing &obj as this, identical in cost to a C func(&obj). The exception is virtual functions: a class with any virtual function gets a hidden vtable pointer (one pointer per object) and dispatch goes through the vtable, that's the one case methods affect size and add indirection, which is why embedded code is cautious with virtuals.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Classes & Encapsulation

Bundle data with the code that operates on it, and hide the internals behind a clean interface: the C struct-plus-functions pattern, made safe by the compiler.

More Classes & Encapsulation questions

Browse all 472 interview questions