All Courses
OOP: APPENDIX

Frequently Asked Questions

This section provides answers to commonly asked questions that aren't strictly interview questions, but rather questions regarding basic application and syntax when using OOP in C++.

Object-Oriented Principles

1. Is C++ a purely Object-Oriented language? No, C++ is a multi-paradigm language. It supports procedural programming, object-oriented programming, and generic programming (templates). Unlike languages like Java or C# where almost everything must be inside a class, C++ allows free-standing functions (like main()) and global variables.

2. Should I always use Object-Oriented Programming in C++? Not necessarily. While OOP is powerful for modeling complex systems with state and behavior, procedural or functional approaches might be better suited for simple scripts, mathematical calculations, or performance-critical embedded systems where the overhead of virtual functions (vtable lookups) is undesirable.

3. What is "Composition over Inheritance"? It's a design principle suggesting that classes should achieve polymorphic behavior and code reuse by containing instances of other classes (composition: a "has-a" relationship) rather than inheriting from a base class (inheritance: an "is-a" relationship). It reduces tight coupling and makes systems more flexible.

Memory & Performance

4. Are objects created on the stack or the heap in C++? Both are possible in C++:

  • Stack: Creating an object like MyClass obj; places it on the stack. The memory is automatically managed and freed when the object goes out of scope.
  • Heap: Creating an object with new (e.g., MyClass* ptr = new MyClass();) allocates it on the heap. You are responsible for deleteing it later (or returning it in an RAII wrapper like a smart pointer).

5. Do virtual functions cause a performance hit? Yes, but it's usually negligible in modern applications. A virtual function call requires a runtime lookup through a virtual method table (vtable) and a pointer dereference. This prevents the compiler from easily inlining the function. For critical hot loops (like in game engines), you might avoid deep inheritance trees to preserve cache locality.

Syntax & Implementation

6. Why use header guards (#ifndef, #pragma once) in class definitions? If a class is defined in a header file, and that header file is included multiple times within the same translation unit (e.g., source file), the compiler will throw a "multiple definition" error. Header guards ensure the contents of an h-file are compiled only once per source file.

7. Can I overload a function solely based on its return type? No. C++ compilers distinguish overloaded functions based on the number and type of arguments (the signature). The return type is not part of the mangled function name used for resolution. If parameter lists are identical, the compiler cannot determine which function to call.