Object Oriented Programming — One Question at a Time
Practise 150 Object-Oriented Programming multiple-choice questions covering classes, objects, constructors, inheritance, polymorphism, C++ templates, exceptions and smart pointers. Work through one question at a time, check the correct answer with an explanation, and select Next Question to continue. This is self-paced practice without automatic scoring.
Before you practise: Read Object-Oriented Programming study material and examples. You can also browse all 1,576 interactive MCQs.
Question 1. In object-oriented programming, what is a class?
Show Answer and Explanation
Correct answer: C. A blueprint defining data and behaviour
A class specifies an object’s attributes and operations.
Question 2. What is an object?
Show Answer and Explanation
Correct answer: A. An instance of a class
An object is an instance with its own identity and state.
Question 3. Which OOP principle bundles data and related methods together?
Show Answer and Explanation
Correct answer: D. Encapsulation
Encapsulation groups attributes and operations within a class.
Question 4. In C++, which access specifier usually makes a member accessible only inside its class and friends?
Show Answer and Explanation
Correct answer: B. private
Private members are inaccessible to unrelated outside code; friends and class members can access them.
Question 5. A class Employee stores name and salary. Which is an example of an instance?
Show Answer and Explanation
Correct answer: B. An Employee object for a specific worker
A specific Employee object represents one entity defined by the Employee class.
Question 6. What is a constructor used for?
Show Answer and Explanation
Correct answer: D. Initializing an object when it is created
Constructors establish initial object state as part of construction.
Question 7. In C++, a class destructor is named using which prefix?
Show Answer and Explanation
Correct answer: A. ~
A C++ destructor has the class name prefixed by a tilde.
Question 8. What is true of a static data member in C++?
Show Answer and Explanation
Correct answer: C. It is associated with the class rather than each instance
A static data member has one class-associated entity, unlike per-object non-static members.
Question 9. In a C++ const member function, what is generally disallowed?
Show Answer and Explanation
Correct answer: D. Changing non-mutable data members
Const member functions normally cannot modify non-mutable state of the object.
Question 10. When is a local C++ object’s destructor normally called?
Show Answer and Explanation
Correct answer: B. When its scope ends
For an automatic local object, destruction normally occurs on exiting its scope.
Question 11. What distinguishes function overloading in C++?
Show Answer and Explanation
Correct answer: C. Same name with different parameter lists
Overloads share a function name but differ in parameter signatures; return type alone is insufficient.
Question 12. What relationship is typically represented by composition?
Show Answer and Explanation
Correct answer: A. A strong whole–part ownership relationship
Composition models parts whose lifetimes are controlled by their whole in typical OO design.
Question 13. Which relation is best described as ‘is-a’?
Show Answer and Explanation
Correct answer: A. Inheritance
Inheritance represents a subtype relationship when designed consistently with substitutability.
Question 14. Which example most naturally illustrates aggregation?
Show Answer and Explanation
Correct answer: C. A department referencing teachers who may exist independently
Aggregation commonly describes a non-owning whole–part relationship where components can exist separately.
Question 15. In C++, what can operator overloading do?
Show Answer and Explanation
Correct answer: B. Define operator behaviour for user-defined types
Operator overloads support user-defined types but cannot create new operators or change precedence.
Question 16. Which access specifier lets derived classes access a C++ base-class member but normally restricts unrelated code?
Show Answer and Explanation
Correct answer: D. protected
Protected members can be used by class members, friends and appropriate derived-class code.
Question 17. What is runtime polymorphism in C++ usually achieved through?
Show Answer and Explanation
Correct answer: C. Virtual functions
Virtual functions allow a call through a base reference or pointer to dispatch to a derived override.
Question 18. What is the purpose of a pure virtual function in C++?
Show Answer and Explanation
Correct answer: D. Require a concrete derived class to provide an implementation, subject to inherited overrides
A pure virtual declaration makes its class abstract; concrete derived classes need a final overrider.
Question 19. If Dog publicly derives from Animal, which is generally an acceptable substitution?
Show Answer and Explanation
Correct answer: B. Use an Animal interface to operate on a Dog
Public inheritance intends substitutability: a Dog is usable through a suitable Animal interface.
Question 20. What does an abstract class in C++ prohibit?
Show Answer and Explanation
Correct answer: A. Directly creating an instance of that abstract class
An abstract class cannot be directly instantiated, though it can serve as a base.
Question 21. What is a C++ function template?
Show Answer and Explanation
Correct answer: B. A function pattern that can generate functions for suitable types
Function templates describe generic operations instantiated for types satisfying their requirements.
Question 22. Which standard C++ container provides contiguous dynamic storage of elements?
Show Answer and Explanation
Correct answer: A. std::vector
std::vector stores elements contiguously and can resize dynamically.
Question 23. For a std::vector<int> v = {2,4,6}, what does v.size() return?
Show Answer and Explanation
Correct answer: D. 3
There are three elements, so size() returns 3.
Question 24. What is the main idea of generic programming?
Show Answer and Explanation
Correct answer: C. Write reusable algorithms parameterized by types or operations
Generic code expresses an algorithm for a family of compatible types.
Question 25. What is the role of a try block in C++ exception handling?
Show Answer and Explanation
Correct answer: D. Mark code whose exceptions may be handled by matching handlers
A try block establishes a region with associated exception handlers.
Question 26. Which keyword explicitly signals an exception in C++?
Show Answer and Explanation
Correct answer: C. throw
The throw expression initiates exception handling.
Question 27. What does serialization generally mean?
Show Answer and Explanation
Correct answer: A. Converting an object’s relevant state to a storable or transferable representation
Serialization encodes state for storage or transfer; deserialization reconstructs it appropriately.
Question 28. Why should input from a serialized file be validated before reconstructing an object?
Show Answer and Explanation
Correct answer: B. A corrupted or untrusted representation may contain invalid data
Validation guards against malformed, incompatible and potentially malicious input.
Question 29. What is the main purpose of a catch block?
Show Answer and Explanation
Correct answer: A. Handle an exception of a matching type
A catch clause processes an exception after it is thrown and matched.
Question 30. Which principle best supports robust exception handling?
Show Answer and Explanation
Correct answer: D. Maintain valid program state when an operation fails
Well-designed code preserves invariants and releases resources when failures occur.
Question 31. A C++ struct differs from a class by default in which way?
Show Answer and Explanation
Correct answer: C. Default member and base access is public for struct
In C++, struct and class support largely the same features, but their default access differs.
Question 32. In C++, what is printed by: class C {public: int x=4;}; C a; C b=a; b.x=9; std::cout<<a.x; ?
Show Answer and Explanation
Correct answer: B. 4
The implicitly generated copy constructor copies the integer member. Modifying b.x does not change a.x, so the program prints 4 (assuming the required iostream header is included).
Question 33. Which initialization invokes a C++ copy constructor?
Show Answer and Explanation
Correct answer: C. Widget b(a);
Constructing b from an existing Widget a selects the copy constructor when applicable.
Question 34. For a member object owned by another C++ object, which is destroyed first when the outer object is destroyed?
Show Answer and Explanation
Correct answer: A. The outer destructor body, then its member objects
The outer destructor body runs before destruction of its non-static member subobjects.
Question 35. Which feature permits initialization of a const data member in C++?
Show Answer and Explanation
Correct answer: D. Constructor member-initializer list
Const data members must be initialized, for example using a member-initializer.
Question 36. If class D publicly inherits B, how are public B members generally accessed through D?
Show Answer and Explanation
Correct answer: B. Remain public
Public inheritance preserves public accessibility for inherited public members.
Question 37. A protected base member under private inheritance becomes what access in the derived class?
Show Answer and Explanation
Correct answer: B. private
Private inheritance makes accessible inherited public/protected base members private within the derived class.
Question 38. Which mechanism addresses repeated virtual base subobjects in diamond inheritance?
Show Answer and Explanation
Correct answer: D. virtual inheritance
Virtual inheritance makes specified common virtual base subobjects shared.
Question 39. What happens if a derived class has a function with the same name as a base-class overload set?
Show Answer and Explanation
Correct answer: A. The derived declaration can hide the base overload set
Name hiding applies unless the base overloads are reintroduced, such as with using B::f.
Question 40. Which keyword explicitly disallows further overriding of a virtual function in C++?
Show Answer and Explanation
Correct answer: C. final
The final specifier prohibits overriding in later derived classes.
Question 41. For virtual void f() and a base reference bound to a derived object, which implementation is invoked?
Show Answer and Explanation
Correct answer: D. The final overrider for the object’s dynamic type
Virtual dispatch selects the final overrider according to the dynamic object type.
Question 42. What does override help the C++ compiler verify?
Show Answer and Explanation
Correct answer: B. That a function really overrides a virtual base function
override requests a compile-time check that the function matches a virtual base declaration.
Question 43. Why should a C++ base class intended for polymorphic deletion normally have a virtual destructor?
Show Answer and Explanation
Correct answer: C. To enable safe deletion via a base pointer
When an object of a derived class is deleted through a pointer to its base type, a virtual base destructor normally ensures the derived and base destructors are invoked correctly. This question assumes ordinary delete through a base pointer.
Question 44. In C++, what is object slicing?
Show Answer and Explanation
Correct answer: A. Copying a derived object into a base object, losing derived-specific state
A base-by-value copy retains only the base subobject.
Question 45. Can a C++ abstract class define non-pure member functions?
Show Answer and Explanation
Correct answer: A. Yes
Abstract classes may have fully implemented methods alongside pure virtual ones.
Question 46. Which declarations are valid C++ function overloads?
Show Answer and Explanation
Correct answer: C. int f(int) and int f(double)
Parameter type differences permit overloading; changing only the return type does not.
Question 47. What is the purpose of an explicit single-argument constructor?
Show Answer and Explanation
Correct answer: B. Prevent unintended implicit converting construction
explicit inhibits implicit conversions through that constructor.
Question 48. What does std::vector::push_back normally do?
Show Answer and Explanation
Correct answer: D. Append an element
push_back adds an element at the end.
Question 49. For std::vector<int> v{8,3,5}; what is v.at(1)?
Show Answer and Explanation
Correct answer: C. 3
at(1) returns the second element and checks bounds.
Question 50. What can happen when std::vector reallocates due to growth?
Show Answer and Explanation
Correct answer: D. References and iterators to existing elements can be invalidated
Moving storage to a larger allocation can invalidate existing pointers, references and iterators.
Question 51. What does a catch(const std::exception& e) handler avoid compared with catch by value?
Show Answer and Explanation
Correct answer: B. Exception object slicing
Catching by reference preserves polymorphism and avoids copying the exception object.
Question 52. What is the role of noexcept on a function declaration?
Show Answer and Explanation
Correct answer: A. State that the function is non-throwing under its exception specification
If an exception escapes a noexcept function, std::terminate is invoked.
Question 53. Which data should normally be included in serialized objects?
Show Answer and Explanation
Correct answer: B. Relevant persistent object state
Persistent representations should encode meaningful data rather than transient process addresses or handles.
Question 54. In C++, what does this print? int x=4; int& r=x; r=9; std::cout<<x;
Show Answer and Explanation
Correct answer: A. 9
r is a reference to x; assigning through r changes x to 9.
Question 55. A class owns a dynamically allocated buffer. Which special member is used when an existing object is assigned from another existing object by copy?
Show Answer and Explanation
Correct answer: D. Copy assignment operator
An assignment expression such as a = b on two existing objects invokes the copy assignment operator when available.
Question 56. What is printed? class A {public: static int f(){return 6;}}; std::cout<<A::f();
Show Answer and Explanation
Correct answer: C. 6
The static member function can be called using the class name and returns 6.
Question 57. What is printed? struct B {virtual int f(){return 1;}}; struct D:B {int f() override {return 5;}}; D d; B& b=d; std::cout<<b.f();
Show Answer and Explanation
Correct answer: D. 5
Virtual dispatch uses D::f because the reference refers to a D object.
Question 58. What is printed? struct C {int n=3; int get() const {return n;}}; const C c; std::cout<<c.get();
Show Answer and Explanation
Correct answer: C. 3
A const member function can read the member of a const object.
Question 59. What is printed? std::vector<int> v{1,2}; v.push_back(3); std::cout<<v.size();
Show Answer and Explanation
Correct answer: A. 3
push_back adds a third element.
Question 60. What is printed? struct X {X(int v):n(v){} int n;}; X a(8); std::cout<<a.n;
Show Answer and Explanation
Correct answer: B. 8
The constructor member initializer assigns n the value 8.
Question 61. What does this print? int n=3; auto f=[n](){return n+2;}; n=10; std::cout<<f();
Show Answer and Explanation
Correct answer: A. 5
Capturing n by value copies 3 at lambda creation, so f returns 5.
Question 62. Which C++ rule applies to the order of non-static data-member initialization?
Show Answer and Explanation
Correct answer: D. Declaration order in the class
Non-static members are initialized in their declaration order, independent of initializer-list order.
Question 63. What does the C++ keyword delete mean in Widget(const Widget&)=delete?
Show Answer and Explanation
Correct answer: C. Disallow use of that copy-constructor overload
A deleted special member cannot be selected for a valid call.
Question 64. Which class is automatically noncopyable because it owns a std::unique_ptr member (unless custom copy support is supplied)?
Show Answer and Explanation
Correct answer: B. A class with a unique_ptr member
unique_ptr is move-only, causing the implicit copy constructor of an owning class to be deleted.
Question 65. What is the main benefit of std::unique_ptr?
Show Answer and Explanation
Correct answer: C. It expresses exclusive ownership and automatic deletion
A unique_ptr owns a dynamically allocated object and frees it when ownership ends.
Question 66. Which pair is required for overriding a C++ virtual function?
Show Answer and Explanation
Correct answer: A. Same name and a compatible parameter signature
An override must match the relevant virtual signature, including cv/ref qualifiers, with allowable return types.
Question 67. A derived object is accessed through a base pointer. Calling a non-virtual method normally selects which implementation?
Show Answer and Explanation
Correct answer: D. Based on static type of the expression
Non-virtual member calls are resolved based on the expression’s static type.
Question 68. In C++, which keyword specifies that a virtual function cannot be overridden further?
Show Answer and Explanation
Correct answer: B. final
final prevents additional overrides of the specified virtual function.
Question 69. Which class design best models a Car containing and owning its Engine value member?
Show Answer and Explanation
Correct answer: B. Composition
A directly contained Engine subobject has lifetime tied to its Car, a standard composition model.
Question 70. When might aggregation be preferable to composition?
Show Answer and Explanation
Correct answer: D. When an associated object has an independent lifetime
Aggregation is suitable for non-owning relationships between independently existing objects.
Question 71. Which declaration is a simple C++ function template?
Show Answer and Explanation
Correct answer: A. template<class T> T id(T x){return x;}
The template parameter T makes id generic over suitable argument types.
Question 72. For std::vector<int> v{10,20,30}, what does v.at(3) do?
Show Answer and Explanation
Correct answer: C. Throws std::out_of_range
The valid indices are 0, 1 and 2. The bounds-checked at(3) throws std::out_of_range.
Question 73. Which C++ construct automatically releases owned resources if an exception unwinds the stack?
Show Answer and Explanation
Correct answer: D. Objects whose destructors follow RAII
Stack unwinding destroys automatic objects, allowing RAII cleanup.
Question 74. What happens if an exception escapes a noexcept function?
Show Answer and Explanation
Correct answer: B. std::terminate is called
Violating a non-throwing exception specification causes termination.
Question 75. Which handler is generally preferable for standard exceptions?
Show Answer and Explanation
Correct answer: C. catch(const std::exception& e)
Catching by const reference avoids slicing and unnecessary copying.
Question 76. Why is serializing a raw pointer’s numerical address generally unsuitable for persistent data?
Show Answer and Explanation
Correct answer: A. The address is not a stable meaningful identity across processes or runs
An in-process address typically cannot be used to reconstruct an object later.
Question 77. For repeated insertion at the back and indexed random access, which STL container is often a good starting choice?
Show Answer and Explanation
Correct answer: A. std::vector
vector supports amortized constant-time push_back and constant-time index access.
Question 78. Why should a class expose a small stable public interface?
Show Answer and Explanation
Correct answer: C. To reduce coupling to its implementation details
An interface limits dependencies on private representation, simplifying maintenance.
Question 79. Given struct Box {int n;}; Box a{3}; Box b=a; b.n+=4; what is a.n?
Show Answer and Explanation
Correct answer: B. 3
Copying a Box copies its integer member. Updating b does not change a.
Question 80. A C++ object contains a std::string member. What handles that member’s cleanup when the object is destroyed?
Show Answer and Explanation
Correct answer: D. The string member’s destructor
Member subobjects are destroyed automatically when their containing object is destroyed.
Question 81. Given struct Counter {inline static int n=0; Counter(){++n;}}; Counter a,b,c; what is Counter::n?
Show Answer and Explanation
Correct answer: C. 3
Three constructor calls increment the shared static member to three.
Question 82. Given int x=2; int& y=x; ++y; what is x?
Show Answer and Explanation
Correct answer: D. 3
y aliases x; incrementing y increments x.
Question 83. What is the danger of returning a reference to a non-static local integer from a C++ function?
Show Answer and Explanation
Correct answer: B. A dangling reference after return
The local integer has automatic storage duration and its lifetime ends when the function returns. The returned reference dangles; using it afterward has undefined behaviour.
Question 84. A Library stores non-owning references to existing Book objects. Which relationship is most natural?
Show Answer and Explanation
Correct answer: A. Aggregation
Independent object lifetimes suggest aggregation.
Question 85. A House owns Room objects stored as direct data members. Which relationship is illustrated?
Show Answer and Explanation
Correct answer: B. Composition
Direct member objects have lifetimes tied to their containing object.
Question 86. Why can publicly deriving Square from a mutable Rectangle with independent width and height setters be problematic?
Show Answer and Explanation
Correct answer: A. A square may violate the rectangle interface’s behavioural expectations
A square requiring equal sides may not satisfy a rectangle interface allowing independent dimensions.
Question 87. Given void f(int); void f(double); which overload is selected by f(2.5)?
Show Answer and Explanation
Correct answer: D. f(double)
The floating-point literal is a double, giving an exact match.
Question 88. Given struct B {virtual int f() const {return 1;}}; struct D:B {int f() const override {return 4;}}; D d; B* p=&d; what is p->f()?
Show Answer and Explanation
Correct answer: C. 4
Virtual dispatch selects the derived override.
Question 89. A derived method g(int) hides its base’s g(double). What can reintroduce the base overload set?
Show Answer and Explanation
Correct answer: D. using Base::g;
A using declaration can expose the base overload set.
Question 90. Given std::vector<int> v{5,10,15}; what is v.front()+v.back()?
Show Answer and Explanation
Correct answer: C. 20
The first and last elements are 5 and 15, whose sum is 20.
Question 91. Which category of iterators is required by std::sort?
Show Answer and Explanation
Correct answer: A. Random-access iterators
std::sort requires random-access iterators.
Question 92. What must be true for a template expression a < b to compile for a substituted type?
Show Answer and Explanation
Correct answer: B. The comparison expression must be valid
Template requirements depend on the operations used on the substituted types.
Question 93. When a constructor throws, what happens to its fully constructed member subobjects?
Show Answer and Explanation
Correct answer: A. Their destructors run
Successfully constructed members are destroyed during exception unwinding.
Question 94. Which C++ smart pointer offers reference-counted shared ownership?
Show Answer and Explanation
Correct answer: D. std::shared_ptr
shared_ptr supports shared ownership through reference counting.
Question 95. What is std::weak_ptr commonly useful for?
Show Answer and Explanation
Correct answer: C. Observing a shared object without owning it
weak_ptr allows non-owning access and can help avoid reference cycles.
Question 96. What does the basic exception-safety guarantee promise?
Show Answer and Explanation
Correct answer: B. Valid invariants and no leaked resources
An operation can modify state but must preserve invariants and avoid leaks.
Question 97. Which condition is essential for a correct equality operator on value objects?
Show Answer and Explanation
Correct answer: C. Reflexivity, symmetry and transitivity
Equality should behave as an equivalence relation, including symmetry and transitivity.
Question 98. Which C++ feature permits a class to inherit from two direct base classes?
Show Answer and Explanation
Correct answer: A. Multiple inheritance
A derived class can list two or more direct base classes.
Question 99. What does virtual inheritance help resolve in a diamond hierarchy?
Show Answer and Explanation
Correct answer: D. Duplicate common base subobjects
A virtual base is shared within the most-derived object rather than duplicated along multiple paths.
Question 100. Which principle says derived objects should uphold the behavioural expectations of their base type?
Show Answer and Explanation
Correct answer: B. Liskov substitution principle
Substitution requires preserving the base abstraction’s contract.
Question 101. Which type is suitable for a non-owning link that breaks a shared_ptr ownership cycle?
Show Answer and Explanation
Correct answer: B. std::weak_ptr
weak_ptr observes a shared object without contributing to shared ownership.
Question 102. Why is shallow copying an owning raw pointer dangerous?
Show Answer and Explanation
Correct answer: D. It can make multiple objects delete the same resource
Two objects can end up believing that they exclusively own the same allocation.
Question 103. What is the Rule of Zero in C++ class design?
Show Answer and Explanation
Correct answer: A. Prefer RAII members that avoid writing custom special member functions
Resource-managing member types let the compiler-generated operations often suffice.
Question 104. What is a class template?
Show Answer and Explanation
Correct answer: C. A pattern for defining a family of classes
Template arguments determine particular instantiations of the class pattern.
Question 105. Which issue can make raw binary serialization nonportable?
Show Answer and Explanation
Correct answer: D. Differences in byte order and object representation
Endianness, padding and type representation may differ across systems.
Question 106. Which exception-safety guarantee promises that a failed operation leaves observable state unchanged?
Show Answer and Explanation
Correct answer: B. Strong guarantee
The strong guarantee gives rollback-like behaviour on an operation’s failure.
Question 107. How can polymorphic object slicing be avoided?
Show Answer and Explanation
Correct answer: C. Use references or pointers to base interfaces
References and pointers preserve the object’s dynamic type.
Question 108. Which design choice most directly prevents a cyclic ownership leak between two std::shared_ptr-managed objects?
Show Answer and Explanation
Correct answer: A. Using std::weak_ptr for one non-owning link
If both objects strongly own one another, their reference counts may never reach zero. Replacing an appropriate strong link with weak_ptr breaks the ownership cycle.
Question 109. What does the C++ access specifier public permit?
Show Answer and Explanation
Correct answer: D. Access from permitted external code
Public class members are generally accessible through valid expressions from outside the class.
Question 110. Which C++ expression creates an automatic local object of class Book?
Show Answer and Explanation
Correct answer: A. Book b;
A declaration such as Book b creates a local object when Book is default-constructible.
Question 111. What is an object’s invariant?
Show Answer and Explanation
Correct answer: B. A property expected to hold in its valid states
Class invariants describe relationships that valid object states preserve.
Question 112. Why might a member be declared private?
Show Answer and Explanation
Correct answer: C. To protect representation details behind an interface
Private access enables controlled use of internal representation.
Question 113. Which principle asks classes to have focused responsibilities?
Show Answer and Explanation
Correct answer: D. Single responsibility principle
Focused responsibilities help reduce unrelated reasons for a class to change.
Question 114. Why are virtual functions useful?
Show Answer and Explanation
Correct answer: A. They enable runtime dispatch through base interfaces
Virtual dispatch selects the final overrider based on a polymorphic object’s dynamic type.
Question 115. What is the purpose of a C++ initializer list in a constructor?
Show Answer and Explanation
Correct answer: B. Initialize bases and data members
Member-initializer lists initialize subobjects before the constructor body.
Question 116. Which expression normally accesses a member via a pointer to an object?
Show Answer and Explanation
Correct answer: C. p->value
The arrow operator accesses a member through a pointer.
Question 117. What does a C++ reference variable generally provide?
Show Answer and Explanation
Correct answer: D. An alias to another object
A reference denotes an existing object or function according to its type.
Question 118. What does the override specifier prevent?
Show Answer and Explanation
Correct answer: A. Accidental failure to match a base virtual function
The compiler checks that an override-designated function overrides a base virtual function.
Question 119. What is dynamic binding?
Show Answer and Explanation
Correct answer: B. Selecting an overridden operation at runtime
Dynamic dispatch resolves virtual calls according to the runtime object type.
Question 120. Which operation cannot be overloaded in C++?
Show Answer and Explanation
Correct answer: C. The scope resolution operator ::
C++ does not allow overloading the scope-resolution operator.
Question 121. What does a default constructor allow when accessible and applicable?
Show Answer and Explanation
Correct answer: D. Construction without explicit arguments
A default constructor can be invoked with no supplied arguments.
Question 122. When should a destructor release resources?
Show Answer and Explanation
Correct answer: A. When the object owns resources that need cleanup
RAII ties the release of owned resources to object lifetime.
Question 123. What can cause a memory leak with raw owning pointers?
Show Answer and Explanation
Correct answer: B. Losing an allocated pointer without releasing its allocation
Unreleased allocations can remain inaccessible and consume memory.
Question 124. What is the C++ rule of five concerned with?
Show Answer and Explanation
Correct answer: C. Copying, moving and destruction for resource-owning classes
The rule of five covers the destructor and copy/move construction and assignment.
Question 125. What is move semantics intended to support?
Show Answer and Explanation
Correct answer: D. Transferring resources from a source object when permitted
Move operations can transfer ownership instead of expensive copying.
Question 126. Which expression constructs a dynamically allocated Widget in C++?
Show Answer and Explanation
Correct answer: A. new Widget()
A new-expression allocates storage and constructs an object.
Question 127. What is the preferred owner for one dynamically allocated object in modern C++?
Show Answer and Explanation
Correct answer: B. std::unique_ptr
unique_ptr expresses exclusive ownership with automatic destruction.
Question 128. What is an interface in object-oriented design?
Show Answer and Explanation
Correct answer: C. A set of operations exposed to clients
An interface defines available interactions without requiring knowledge of implementation details.
Question 129. What is a key benefit of composition over unnecessary inheritance?
Show Answer and Explanation
Correct answer: D. It can reuse behavior without creating an is-a relationship
Composition models has-a relationships and can reduce coupling.
Question 130. What is dependency injection?
Show Answer and Explanation
Correct answer: A. Providing collaborators to an object from outside
External collaborators make dependencies explicit and easier to substitute in tests.
Question 131. What does const correctness help express?
Show Answer and Explanation
Correct answer: B. Which operations should not modify an object
Const qualifiers communicate and help enforce nonmodifying access.
Question 132. When an exception is thrown, what is stack unwinding?
Show Answer and Explanation
Correct answer: C. Destroying completed automatic objects as scopes are exited
Unwinding leaves active scopes while destructors perform cleanup.
Question 133. Which standard container offers key-value mappings with ordered keys?
Show Answer and Explanation
Correct answer: D. std::map
std::map maintains an ordered associative mapping.
Question 134. Which standard container supports average constant-time key lookup under typical hashing assumptions?
Show Answer and Explanation
Correct answer: A. std::unordered_map
Hash-based unordered maps have average constant-time search under suitable hashing.
Question 135. What is a template specialization?
Show Answer and Explanation
Correct answer: B. A customized template definition for particular arguments
Specialization can provide behavior for selected template arguments.
Question 136. What is a lambda expression in modern C++?
Show Answer and Explanation
Correct answer: C. A way to define a function object inline
A lambda creates a callable closure object.
Question 137. What is a virtual destructor particularly important for?
Show Answer and Explanation
Correct answer: D. Deleting derived objects through base pointers
A virtual base destructor ensures complete polymorphic destruction.
Question 138. What is a copy constructor expected to initialize?
Show Answer and Explanation
Correct answer: A. A new object using another object
Copy construction creates a distinct object from a source object.
Question 139. What does operator= typically do for an existing object?
Show Answer and Explanation
Correct answer: B. Assign a new state to the existing object
The assignment operator updates an already constructed object.
Question 140. What is the purpose of unit testing a class?
Show Answer and Explanation
Correct answer: C. Verify individual methods and object behavior
Unit tests exercise defined class behavior against expectations.
Question 141. Which SOLID guideline favors adding behavior without editing stable existing code?
Show Answer and Explanation
Correct answer: D. Open-closed principle
The open-closed principle encourages extension while limiting modification.
Question 142. What is a covariant return type permitted in certain C++ overrides?
Show Answer and Explanation
Correct answer: A. A pointer or reference to a more-derived class type
C++ allows certain covariant class pointer/reference return types for virtual overrides.
Question 143. Can constructors in C++ themselves be virtual?
Show Answer and Explanation
Correct answer: B. No
Construction establishes dynamic type, and C++ constructors cannot be virtual.
Question 144. What does the nullptr literal represent in C++?
Show Answer and Explanation
Correct answer: C. A null pointer value
nullptr is the dedicated null pointer literal.
Question 145. What is the benefit of using an enum class over an unscoped enum?
Show Answer and Explanation
Correct answer: D. Stronger scoping and type safety
Scoped enumerations limit unintended name and implicit conversion conflicts.
Question 146. What is an object’s dynamic type in a polymorphic hierarchy?
Show Answer and Explanation
Correct answer: A. The type of the actual most-derived object
Virtual dispatch follows the dynamic type of the object, not merely the pointer’s static type.
Question 147. Which design pattern creates objects through an interface rather than exposing construction details?
Show Answer and Explanation
Correct answer: B. Factory method
A factory method delegates object creation through an abstraction.
Question 148. Why use a virtual function’s base interface rather than downcasting routinely?
Show Answer and Explanation
Correct answer: C. To reduce dependence on concrete derived types
Working through a base abstraction improves substitutability and decoupling.
Question 149. What does std::make_unique<T>() typically return?
Show Answer and Explanation
Correct answer: D. A std::unique_ptr<T> owning a newly created T
make_unique constructs an object and returns an exclusive-ownership smart pointer.
Question 150. What does a const reference parameter often help avoid?
Show Answer and Explanation
Correct answer: A. Unnecessary copying of the passed object
Passing by const reference allows read-only access without copying large objects.
