Object Oriented Programming
Introduction
Understand how software can be designed around interacting objects and reusable classes.
Topic-Wise Overview
Core Concepts
Classes, objects, encapsulation, access control and object relationships
Object Lifecycle
Constructors, destructors, static members and const functions
Reusability
Overloading, composition, aggregation and inheritance
Abstraction and Polymorphism
Polymorphism, abstract classes and interfaces
Advanced Features
Templates, standard template library, serialization and exception handling
Question Bank Navigation
Use the links below to jump directly to each practice set. The questions remain numbered in order, and each MCQ includes an expandable answer.
- Topic-Wise Practice MCQs — Foundation Set
- Additional Topic-Wise MCQs — Questions 31–53
- Applied and Advanced MCQs — Questions 54–78
- Further Applied MCQs — Questions 79–96
- Additional Topic Questions 97–108
- Short Questions and Answers
- Practical C++ Programming Exercises
Study tip: Begin with the foundational questions, then move to applied questions and programming exercises. Labels indicate practice groupings, not formal exam difficulty ratings.
Study Guidance
Start with the core definitions, follow practical examples and check your understanding with independent exercises. Study the initial practice set below, and review the explanations before attempting the exercises.
Topic-Wise Practice MCQs — Foundation Set
These 30 MCQs introduce key concepts in the supplied object-oriented programming outline. Most code-specific explanations use C++ conventions. Expand each answer to read the explanation.
Classes and Objects
Q1. In object-oriented programming, what is a class?
- A. A hardware register
- B. A compiler error
- C. A blueprint defining data and behaviour
- D. A single running process
Show correct answer and explanation
Correct answer: C. A blueprint defining data and behaviour
A class specifies an object’s attributes and operations.
Q2. What is an object?
- A. An instance of a class
- B. A type of source-file extension
- C. Only a static method
- D. Only a function name
Show correct answer and explanation
Correct answer: A. An instance of a class
An object is an instance with its own identity and state.
Q3. Which OOP principle bundles data and related methods together?
- A. Compilation
- B. Recursion
- C. Sorting
- D. Encapsulation
Show correct answer and explanation
Correct answer: D. Encapsulation
Encapsulation groups attributes and operations within a class.
Q4. In C++, which access specifier usually makes a member accessible only inside its class and friends?
- A. global
- B. private
- C. public
- D. protected
Show correct answer and explanation
Correct answer: B. private
Private members are inaccessible to unrelated outside code; friends and class members can access them.
Q5. A class Employee stores name and salary. Which is an example of an instance?
- A. The word ‘class’
- B. An Employee object for a specific worker
- C. The C++ compiler
- D. A programming paradigm
Show correct 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.
Object Lifecycle
Q6. What is a constructor used for?
- A. Deleting all source files
- B. Ending a loop
- C. Compiling a program
- D. Initializing an object when it is created
Show correct answer and explanation
Correct answer: D. Initializing an object when it is created
Constructors establish initial object state as part of construction.
Q7. In C++, a class destructor is named using which prefix?
- A. ~
- B. #
- C. %
- D. @
Show correct answer and explanation
Correct answer: A. ~
A C++ destructor has the class name prefixed by a tilde.
Q8. What is true of a static data member in C++?
- A. It always belongs separately to each object
- B. It cannot store numbers
- C. It is associated with the class rather than each instance
- D. It is available only during compilation
Show correct 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.
Q9. In a C++ const member function, what is generally disallowed?
- A. Reading data members
- B. Calling other const functions
- C. Returning values
- D. Changing non-mutable data members
Show correct answer and explanation
Correct answer: D. Changing non-mutable data members
Const member functions normally cannot modify non-mutable state of the object.
Q10. When is a local C++ object’s destructor normally called?
- A. Only when the computer shuts down
- B. When its scope ends
- C. At the beginning of source compilation
- D. After each arithmetic operation
Show correct answer and explanation
Correct answer: B. When its scope ends
For an automatic local object, destruction normally occurs on exiting its scope.
Overloading and Relationships
Q11. What distinguishes function overloading in C++?
- A. Only using recursion
- B. Only a different return type
- C. Same name with different parameter lists
- D. Only a different comment
Show correct 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.
Q12. What relationship is typically represented by composition?
- A. A strong whole–part ownership relationship
- B. A random numeric comparison
- C. A source-code comment
- D. Only a function call
Show correct 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.
Q13. Which relation is best described as ‘is-a’?
- A. Inheritance
- B. File input
- C. Aggregation
- D. Composition
Show correct answer and explanation
Correct answer: A. Inheritance
Inheritance represents a subtype relationship when designed consistently with substitutability.
Q14. Which example most naturally illustrates aggregation?
- A. A function computing 2+2
- B. An integer division
- C. A department referencing teachers who may exist independently
- D. A constructor assigning x = 0
Show correct 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.
Q15. In C++, what can operator overloading do?
- A. Alter precedence of existing operators
- B. Define operator behaviour for user-defined types
- C. Create a completely new operator symbol
- D. Change every built-in integer addition
Show correct 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.
Inheritance and Polymorphism
Q16. Which access specifier lets derived classes access a C++ base-class member but normally restricts unrelated code?
- A. namespace
- B. private
- C. public
- D. protected
Show correct answer and explanation
Correct answer: D. protected
Protected members can be used by class members, friends and appropriate derived-class code.
Q17. What is runtime polymorphism in C++ usually achieved through?
- A. Only arrays
- B. Preprocessor comments
- C. Virtual functions
- D. Only global variables
Show correct 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.
Q18. What is the purpose of a pure virtual function in C++?
- A. Guarantee every object is deleted
- B. Ban all inheritance
- C. Change arithmetic precedence
- D. Require a concrete derived class to provide an implementation, subject to inherited overrides
Show correct 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.
Q19. If Dog publicly derives from Animal, which is generally an acceptable substitution?
- A. Convert Dog into an integer
- B. Use an Animal interface to operate on a Dog
- C. Use any Animal automatically as a Dog
- D. Treat every class as unrelated
Show correct 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.
Q20. What does an abstract class in C++ prohibit?
- A. Directly creating an instance of that abstract class
- B. Declaring data members
- C. Declaring methods
- D. Being used as a base class
Show correct 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.
Templates and Collections
Q21. What is a C++ function template?
- A. A file permission
- B. A function pattern that can generate functions for suitable types
- C. A database schema
- D. A storage device
Show correct 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.
Q22. Which standard C++ container provides contiguous dynamic storage of elements?
- A. std::vector
- B. std::list
- C. std::set
- D. std::map
Show correct answer and explanation
Correct answer: A. std::vector
std::vector stores elements contiguously and can resize dynamically.
Q23. For a std::vector<int> v = {2,4,6}, what does v.size() return?
- A. 6
- B. 2
- C. 4
- D. 3
Show correct answer and explanation
Correct answer: D. 3
There are three elements, so size() returns 3.
Q24. What is the main idea of generic programming?
- A. Always use global variables
- B. Store source code only in a database
- C. Write reusable algorithms parameterized by types or operations
- D. Avoid all type checking
Show correct 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.
Exceptions and Serialization
Q25. What is the role of a try block in C++ exception handling?
- A. Prevent all runtime errors
- B. Write a file without I/O
- C. Declare an inheritance relationship
- D. Mark code whose exceptions may be handled by matching handlers
Show correct 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.
Q26. Which keyword explicitly signals an exception in C++?
- A. catch
- B. class
- C. throw
- D. const
Show correct answer and explanation
Correct answer: C. throw
The throw expression initiates exception handling.
Q27. What does serialization generally mean?
- A. Converting an object’s relevant state to a storable or transferable representation
- B. Removing every class from a program
- C. Sorting a vector automatically
- D. Checking whether a number is prime
Show correct 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.
Q28. Why should input from a serialized file be validated before reconstructing an object?
- A. Every file is always secure
- B. A corrupted or untrusted representation may contain invalid data
- C. Validation changes the compiler version
- D. There are no possible parsing errors
Show correct answer and explanation
Correct answer: B. A corrupted or untrusted representation may contain invalid data
Validation guards against malformed, incompatible and potentially malicious input.
Q29. What is the main purpose of a catch block?
- A. Handle an exception of a matching type
- B. Automatically compile another file
- C. Define a template
- D. Construct an array
Show correct 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.
Q30. Which principle best supports robust exception handling?
- A. Ignore all errors
- B. Assume inputs can never fail
- C. Use exceptions for every loop iteration
- D. Maintain valid program state when an operation fails
Show correct 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.
Short Questions and Answers
1. Differentiate class and object.
A class defines the data and operations shared by a type. An object is an individual instance of that class. For example, Student is a class and one student’s record is an object.
2. Explain encapsulation and data hiding.
Encapsulation groups data with methods. Data hiding controls external access to representation details, commonly through private members and public methods. These concepts are related but not identical.
3. Differentiate composition, aggregation and inheritance.
Composition represents strongly owned parts; aggregation represents parts that can exist independently; inheritance represents a subtype (is-a) relationship. Choose based on actual behaviour and lifetime requirements.
4. Distinguish overloading and overriding in C++.
Overloading gives functions the same name but different parameter signatures. Overriding replaces a virtual base-class operation in a derived class with a matching signature and appropriate return type.
5. Why are destructors and RAII useful in C++?
A destructor performs cleanup when an object’s lifetime ends. RAII ties resource ownership to object lifetime, allowing cleanup on normal scope exit and during stack unwinding.
Practical C++ Programming Exercises
The original course description allows multiple languages. These examples use modern C++ to demonstrate classes, objects, polymorphism, templates and exceptions.
Exercise 1: Class and Constructor
Problem: Create a Rectangle class that validates its dimensions and computes area.
Step-by-step approach: Step 1: Store width and height privately. Step 2: Initialise them in the constructor. Step 3: Reject nonpositive values. Step 4: Return the product in area().
C++ Code
#include <iostream>
#include <stdexcept>
class Rectangle {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {
if (w <= 0 || h <= 0)
throw std::invalid_argument("positive dimensions required");
}
double area() const { return width * height; }
};
int main() {
Rectangle r(4, 3);
std::cout << r.area() << '\n';
}Expected output: 12
Explanation: The constructor initializes a valid rectangle; area() multiplies 4 by 3.
Exercise 2: Inheritance and Runtime Polymorphism
Problem: Create a base class Shape and a derived class Circle with a virtual area method.
Step-by-step approach: Step 1: Define a virtual area() in Shape. Step 2: Derive Circle and override area(). Step 3: Call the method through a base reference.
C++ Code
#include <iostream>
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() = default;
};
class Circle : public Shape {
double radius;
public:
explicit Circle(double r) : radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
};
int main() {
Circle circle(2);
const Shape& shape = circle;
std::cout << shape.area() << '\n';
}Expected output: 12.5664
Explanation: Dynamic dispatch calls Circle::area() through the Shape reference. The value is rounded by the default stream formatting.
Exercise 3: Function Templates
Problem: Write a function template to return the larger of two values and demonstrate it with integers.
Step-by-step approach: Step 1: Declare a template type T. Step 2: Compare two values. Step 3: Return the larger one and print the result.
C++ Code
#include <iostream>
template <typename T>
T larger(T a, T b) {
return (a < b) ? b : a;
}
int main() {
std::cout << larger(7, 12) << '\n';
}Expected output: 12
Explanation: The template is instantiated for integers, and the conditional expression returns 12.
Exercise 4: Exception Handling
Problem: Demonstrate a checked division function with a thrown exception for a zero divisor.
Step-by-step approach: Step 1: Check the denominator. Step 2: Throw an exception if it is zero. Step 3: Handle the exception in main.
C++ Code
#include <iostream>
#include <stdexcept>
double divide(double a, double b) {
if (b == 0) throw std::invalid_argument("zero divisor");
return a / b;
}
int main() {
try {
std::cout << divide(10, 0) << '\n';
} catch (const std::invalid_argument& e) {
std::cout << e.what() << '\n';
}
}Expected output: zero divisor
Explanation: The zero divisor triggers invalid_argument; the catch handler prints its message instead of the quotient.
This is an initial practice set rather than a complete bank for all topics. Additional exercises can cover composition, aggregation, operator overloading, serialization and standard library use in more depth.
Additional Topic-Wise MCQs — Questions 31–53
New conceptual, application and code-behaviour questions with expandable answers and explanations.
C++ Access and Lifetime
Q31. A C++ struct differs from a class by default in which way?
- A. A class cannot have constructors
- B. A struct cannot inherit
- C. Default member and base access is public for struct
- D. A struct cannot have methods
Show correct 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.
Q32. In C++, what is printed by: class C {public: int x=4;}; C a; C b=a; b.x=9; std::cout<<a.x; ?
- A. 9
- B. 4
- C. 13
- D. Undefined
Show correct 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).
Q33. Which initialization invokes a C++ copy constructor?
- A. delete p;
- B. sizeof(Widget);
- C. Widget b(a);
- D. Widget* p=nullptr;
Show correct answer and explanation
Correct answer: C. Widget b(a);
Constructing b from an existing Widget a selects the copy constructor when applicable.
Q34. For a member object owned by another C++ object, which is destroyed first when the outer object is destroyed?
- A. The outer destructor body, then its member objects
- B. Neither ever
- C. The compiler
- D. Its members before its destructor body
Show correct 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.
Q35. Which feature permits initialization of a const data member in C++?
- A. Assignment in the constructor body
- B. A loop after construction
- C. A destructor
- D. Constructor member-initializer list
Show correct answer and explanation
Correct answer: D. Constructor member-initializer list
Const data members must be initialized, for example using a member-initializer.
Inheritance
Q36. If class D publicly inherits B, how are public B members generally accessed through D?
- A. Become private automatically
- B. Remain public
- C. Become inaccessible
- D. Become static
Show correct answer and explanation
Correct answer: B. Remain public
Public inheritance preserves public accessibility for inherited public members.
Q37. A protected base member under private inheritance becomes what access in the derived class?
- A. protected
- B. private
- C. global
- D. public
Show correct answer and explanation
Correct answer: B. private
Private inheritance makes accessible inherited public/protected base members private within the derived class.
Q38. Which mechanism addresses repeated virtual base subobjects in diamond inheritance?
- A. method overloading
- B. operator precedence
- C. file serialization
- D. virtual inheritance
Show correct answer and explanation
Correct answer: D. virtual inheritance
Virtual inheritance makes specified common virtual base subobjects shared.
Q39. What happens if a derived class has a function with the same name as a base-class overload set?
- A. The derived declaration can hide the base overload set
- B. All are deleted
- C. The program must use virtual inheritance
- D. Base overloads are always automatically visible
Show correct 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.
Q40. Which keyword explicitly disallows further overriding of a virtual function in C++?
- A. friend
- B. static
- C. final
- D. mutable
Show correct answer and explanation
Correct answer: C. final
The final specifier prohibits overriding in later derived classes.
Polymorphism and Abstraction
Q41. For virtual void f() and a base reference bound to a derived object, which implementation is invoked?
- A. Neither
- B. The first declared method alphabetically
- C. Always the base
- D. The final overrider for the object’s dynamic type
Show correct 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.
Q42. What does override help the C++ compiler verify?
- A. That a template is always optimized
- B. That a function really overrides a virtual base function
- C. That a loop terminates
- D. That data is encrypted
Show correct 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.
Q43. Why should a C++ base class intended for polymorphic deletion normally have a virtual destructor?
- A. To avoid constructors
- B. To speed up file reads
- C. To enable safe deletion via a base pointer
- D. To make all members public
Show correct 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.
Q44. In C++, what is object slicing?
- A. Copying a derived object into a base object, losing derived-specific state
- B. Allocating an array
- C. Writing an object to file
- D. Splitting a string
Show correct 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.
Q45. Can a C++ abstract class define non-pure member functions?
- A. Yes
- B. Only static functions
- C. Only constructors
- D. No
Show correct answer and explanation
Correct answer: A. Yes
Abstract classes may have fully implemented methods alongside pure virtual ones.
Overloading and Operators
Q46. Which declarations are valid C++ function overloads?
- A. Only functions with different names
- B. int f(int) and double f(int)
- C. int f(int) and int f(double)
- D. int f(int) twice
Show correct 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.
Q47. What is the purpose of an explicit single-argument constructor?
- A. Force inheritance
- B. Prevent unintended implicit converting construction
- C. Make an object immutable
- D. Allow only heap allocation
Show correct answer and explanation
Correct answer: B. Prevent unintended implicit converting construction
explicit inhibits implicit conversions through that constructor.
Templates and STL
Q48. What does std::vector::push_back normally do?
- A. Erase the first element
- B. Sort the vector
- C. Return its capacity
- D. Append an element
Show correct answer and explanation
Correct answer: D. Append an element
push_back adds an element at the end.
Q49. For std::vector<int> v{8,3,5}; what is v.at(1)?
- A. An exception
- B. 8
- C. 3
- D. 5
Show correct answer and explanation
Correct answer: C. 3
at(1) returns the second element and checks bounds.
Q50. What can happen when std::vector reallocates due to growth?
- A. The vector becomes a set
- B. Every element becomes zero
- C. Its size must become zero
- D. References and iterators to existing elements can be invalidated
Show correct 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.
Exceptions and Serialization
Q51. What does a catch(const std::exception& e) handler avoid compared with catch by value?
- A. All possible errors
- B. Exception object slicing
- C. All compiler diagnostics
- D. Every memory allocation
Show correct answer and explanation
Correct answer: B. Exception object slicing
Catching by reference preserves polymorphism and avoids copying the exception object.
Q52. What is the role of noexcept on a function declaration?
- A. State that the function is non-throwing under its exception specification
- B. Turn the function into a constructor
- C. Encrypt arguments
- D. Make all calls constexpr
Show correct 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.
Q53. Which data should normally be included in serialized objects?
- A. Uninitialised memory bytes
- B. Relevant persistent object state
- C. Raw process-specific pointer addresses
- D. Open operating-system file handles
Show correct answer and explanation
Correct answer: B. Relevant persistent object state
Persistent representations should encode meaningful data rather than transient process addresses or handles.
Applied and Advanced MCQs — Questions 54–78
Additional application, code-tracing and concept questions. C++ conventions apply to OOP questions; standard algorithm/data-structure models apply to Data Structures.
Code Tracing
Q54. In C++, what does this print? int x=4; int& r=x; r=9; std::cout<<x;
- A. 9
- B. 13
- C. Compilation error
- D. 4
Show correct answer and explanation
Correct answer: A. 9
r is a reference to x; assigning through r changes x to 9.
Q55. A class owns a dynamically allocated buffer. Which special member is used when an existing object is assigned from another existing object by copy?
- A. Default constructor
- B. Conversion constructor
- C. Destructor
- D. Copy assignment operator
Show correct 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.
Q56. What is printed? class A {public: static int f(){return 6;}}; std::cout<<A::f();
- A. Compilation error
- B. 0
- C. 6
- D. A
Show correct answer and explanation
Correct answer: C. 6
The static member function can be called using the class name and returns 6.
Q57. 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();
- A. 0
- B. Compilation error
- C. 1
- D. 5
Show correct answer and explanation
Correct answer: D. 5
Virtual dispatch uses D::f because the reference refers to a D object.
Q58. What is printed? struct C {int n=3; int get() const {return n;}}; const C c; std::cout<<c.get();
- A. Undefined
- B. 0
- C. 3
- D. Compiler error
Show correct answer and explanation
Correct answer: C. 3
A const member function can read the member of a const object.
Q59. What is printed? std::vector<int> v{1,2}; v.push_back(3); std::cout<<v.size();
- A. 3
- B. 4
- C. 0
- D. 2
Show correct answer and explanation
Correct answer: A. 3
push_back adds a third element.
Q60. What is printed? struct X {X(int v):n(v){} int n;}; X a(8); std::cout<<a.n;
- A. 1
- B. 8
- C. Undefined
- D. 0
Show correct answer and explanation
Correct answer: B. 8
The constructor member initializer assigns n the value 8.
Q61. What does this print? int n=3; auto f=[n](){return n+2;}; n=10; std::cout<<f();
- A. 5
- B. 12
- C. 10
- D. Compilation error
Show correct answer and explanation
Correct answer: A. 5
Capturing n by value copies 3 at lambda creation, so f returns 5.
Constructors and Lifetime
Q62. Which C++ rule applies to the order of non-static data-member initialization?
- A. Alphabetical member names
- B. Random order
- C. Order written in constructor initializer list
- D. Declaration order in the class
Show correct 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.
Q63. What does the C++ keyword delete mean in Widget(const Widget&)=delete?
- A. Enable garbage collection
- B. Delete every Widget object
- C. Disallow use of that copy-constructor overload
- D. Make the function virtual
Show correct answer and explanation
Correct answer: C. Disallow use of that copy-constructor overload
A deleted special member cannot be selected for a valid call.
Q64. Which class is automatically noncopyable because it owns a std::unique_ptr member (unless custom copy support is supplied)?
- A. A class with a bool member
- B. A class with a unique_ptr member
- C. A class with an int member
- D. An empty struct
Show correct 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.
Q65. What is the main benefit of std::unique_ptr?
- A. It forces allocation on the stack
- B. It permits arbitrary shared ownership
- C. It expresses exclusive ownership and automatic deletion
- D. It stores only integers
Show correct 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.
Polymorphism
Q66. Which pair is required for overriding a C++ virtual function?
- A. Same name and a compatible parameter signature
- B. Same name with unrelated parameter types
- C. Only a different return type
- D. Same source-file line
Show correct 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.
Q67. A derived object is accessed through a base pointer. Calling a non-virtual method normally selects which implementation?
- A. Always the most-derived type
- B. A randomly chosen implementation
- C. A template specialization
- D. Based on static type of the expression
Show correct 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.
Q68. In C++, which keyword specifies that a virtual function cannot be overridden further?
- A. override
- B. final
- C. private
- D. friend
Show correct answer and explanation
Correct answer: B. final
final prevents additional overrides of the specified virtual function.
Relationships
Q69. Which class design best models a Car containing and owning its Engine value member?
- A. Only a function overload
- B. Composition
- C. Public inheritance
- D. An unrelated namespace
Show correct answer and explanation
Correct answer: B. Composition
A directly contained Engine subobject has lifetime tied to its Car, a standard composition model.
Q70. When might aggregation be preferable to composition?
- A. When ownership must be exclusive
- B. When every part must be destroyed with the whole
- C. When compilation is forbidden
- D. When an associated object has an independent lifetime
Show correct 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.
Templates
Q71. Which declaration is a simple C++ function template?
- A. template<class T> T id(T x){return x;}
- B. int id(int); int id(int);
- C. class T = int;
- D. virtual template<class T> void f();
Show correct 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.
Q72. For std::vector<int> v{10,20,30}, what does v.at(3) do?
- A. Returns 10
- B. Returns 30
- C. Throws std::out_of_range
- D. Appends a new element
Show correct 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.
Exceptions
Q73. Which C++ construct automatically releases owned resources if an exception unwinds the stack?
- A. Unmanaged raw allocations
- B. Ignoring every exception
- C. Only global arrays
- D. Objects whose destructors follow RAII
Show correct answer and explanation
Correct answer: D. Objects whose destructors follow RAII
Stack unwinding destroys automatic objects, allowing RAII cleanup.
Q74. What happens if an exception escapes a noexcept function?
- A. It is silently ignored
- B. std::terminate is called
- C. The function retries automatically
- D. The compiler inserts a catch
Show correct answer and explanation
Correct answer: B. std::terminate is called
Violating a non-throwing exception specification causes termination.
Q75. Which handler is generally preferable for standard exceptions?
- A. catch(std::string*)
- B. catch(std::exception e)
- C. catch(const std::exception& e)
- D. catch(int*)
Show correct answer and explanation
Correct answer: C. catch(const std::exception& e)
Catching by const reference avoids slicing and unnecessary copying.
Serialization
Q76. Why is serializing a raw pointer’s numerical address generally unsuitable for persistent data?
- A. The address is not a stable meaningful identity across processes or runs
- B. Pointers never have addresses
- C. Files cannot hold digits
- D. All pointer values are zero
Show correct 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.
STL and Design
Q77. For repeated insertion at the back and indexed random access, which STL container is often a good starting choice?
- A. std::vector
- B. std::forward_list
- C. std::stack
- D. std::priority_queue
Show correct answer and explanation
Correct answer: A. std::vector
vector supports amortized constant-time push_back and constant-time index access.
Q78. Why should a class expose a small stable public interface?
- A. To make data necessarily global
- B. To avoid constructors
- C. To reduce coupling to its implementation details
- D. To forbid testing
Show correct answer and explanation
Correct answer: C. To reduce coupling to its implementation details
An interface limits dependencies on private representation, simplifying maintenance.
Further Applied MCQs — Questions 79–96
Advanced conceptual, code-based and application questions with explanations. C++ conventions are used in OOP questions; standard data-structure assumptions are used elsewhere.
Object Semantics
Q79. Given struct Box {int n;}; Box a{3}; Box b=a; b.n+=4; what is a.n?
- A. Undefined
- B. 3
- C. 4
- D. 7
Show correct answer and explanation
Correct answer: B. 3
Copying a Box copies its integer member. Updating b does not change a.
Q80. A C++ object contains a std::string member. What handles that member’s cleanup when the object is destroyed?
- A. A compiler warning
- B. Deleting the source file
- C. Manual free() in every caller
- D. The string member’s destructor
Show correct answer and explanation
Correct answer: D. The string member’s destructor
Member subobjects are destroyed automatically when their containing object is destroyed.
Q81. Given struct Counter {inline static int n=0; Counter(){++n;}}; Counter a,b,c; what is Counter::n?
- A. 1
- B. 2
- C. 3
- D. 0
Show correct answer and explanation
Correct answer: C. 3
Three constructor calls increment the shared static member to three.
Q82. Given int x=2; int& y=x; ++y; what is x?
- A. 0
- B. Undefined
- C. 2
- D. 3
Show correct answer and explanation
Correct answer: D. 3
y aliases x; incrementing y increments x.
Q83. What is the danger of returning a reference to a non-static local integer from a C++ function?
- A. A safe persistent reference
- B. A dangling reference after return
- C. A required deep copy
- D. Automatic heap allocation
Show correct 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.
Relationships
Q84. A Library stores non-owning references to existing Book objects. Which relationship is most natural?
- A. Aggregation
- B. Public inheritance from Book
- C. Operator overloading
- D. Exclusive composition
Show correct answer and explanation
Correct answer: A. Aggregation
Independent object lifetimes suggest aggregation.
Q85. A House owns Room objects stored as direct data members. Which relationship is illustrated?
- A. No ownership
- B. Composition
- C. Virtual dispatch
- D. Generic programming
Show correct answer and explanation
Correct answer: B. Composition
Direct member objects have lifetimes tied to their containing object.
Q86. Why can publicly deriving Square from a mutable Rectangle with independent width and height setters be problematic?
- A. A square may violate the rectangle interface’s behavioural expectations
- B. It prevents compilation in every case
- C. It makes all members static
- D. It always improves substitution
Show correct 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.
Overloading and Dispatch
Q87. Given void f(int); void f(double); which overload is selected by f(2.5)?
- A. Both
- B. Necessarily ambiguous
- C. f(int)
- D. f(double)
Show correct answer and explanation
Correct answer: D. f(double)
The floating-point literal is a double, giving an exact match.
Q88. 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()?
- A. Undefined
- B. 1
- C. 4
- D. 5
Show correct answer and explanation
Correct answer: C. 4
Virtual dispatch selects the derived override.
Q89. A derived method g(int) hides its base’s g(double). What can reintroduce the base overload set?
- A. static Base::g;
- B. friend Base::g;
- C. delete Base::g;
- D. using Base::g;
Show correct answer and explanation
Correct answer: D. using Base::g;
A using declaration can expose the base overload set.
Templates and STL
Q90. Given std::vector<int> v{5,10,15}; what is v.front()+v.back()?
- A. 30
- B. 15
- C. 20
- D. 25
Show correct answer and explanation
Correct answer: C. 20
The first and last elements are 5 and 15, whose sum is 20.
Q91. Which category of iterators is required by std::sort?
- A. Random-access iterators
- B. Only output iterators
- C. Only input iterators
- D. No iterators
Show correct answer and explanation
Correct answer: A. Random-access iterators
std::sort requires random-access iterators.
Q92. What must be true for a template expression a < b to compile for a substituted type?
- A. No instantiation can occur
- B. The comparison expression must be valid
- C. Every type must be a pointer
- D. The type must be int
Show correct answer and explanation
Correct answer: B. The comparison expression must be valid
Template requirements depend on the operations used on the substituted types.
Exceptions and Ownership
Q93. When a constructor throws, what happens to its fully constructed member subobjects?
- A. Their destructors run
- B. They always leak
- C. The complete object’s destructor body runs
- D. They survive indefinitely
Show correct answer and explanation
Correct answer: A. Their destructors run
Successfully constructed members are destroyed during exception unwinding.
Q94. Which C++ smart pointer offers reference-counted shared ownership?
- A. std::weak_ptr alone
- B. Non-owning raw pointer
- C. std::unique_ptr
- D. std::shared_ptr
Show correct answer and explanation
Correct answer: D. std::shared_ptr
shared_ptr supports shared ownership through reference counting.
Q95. What is std::weak_ptr commonly useful for?
- A. Replacing every constructor
- B. Creating a strong ownership cycle
- C. Observing a shared object without owning it
- D. Exclusive destruction
Show correct 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.
Q96. What does the basic exception-safety guarantee promise?
- A. Success always
- B. Valid invariants and no leaked resources
- C. Absolutely unchanged values
- D. No thrown exceptions
Show correct answer and explanation
Correct answer: B. Valid invariants and no leaked resources
An operation can modify state but must preserve invariants and avoid leaks.
Quality Review — New Topic Questions 97–108
Additional questions selected to strengthen underrepresented topics, with answer explanations.
Class Design
Q97. Which condition is essential for a correct equality operator on value objects?
- A. Multiple inheritance
- B. A virtual destructor in every class
- C. Reflexivity, symmetry and transitivity
- D. Automatic dynamic allocation
Show correct answer and explanation
Correct answer: C. Reflexivity, symmetry and transitivity
Equality should behave as an equivalence relation, including symmetry and transitivity.
Q98. Which C++ feature permits a class to inherit from two direct base classes?
- A. Multiple inheritance
- B. Function hiding
- C. Serialization
- D. Single inheritance
Show correct answer and explanation
Correct answer: A. Multiple inheritance
A derived class can list two or more direct base classes.
Q99. What does virtual inheritance help resolve in a diamond hierarchy?
- A. Every compiler warning
- B. Overloaded operators
- C. Invalid input
- D. Duplicate common base subobjects
Show correct 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.
Q100. Which principle says derived objects should uphold the behavioural expectations of their base type?
- A. Greedy choice property
- B. Liskov substitution principle
- C. FIFO principle
- D. Hashing principle
Show correct answer and explanation
Correct answer: B. Liskov substitution principle
Substitution requires preserving the base abstraction’s contract.
Resource Management
Q101. Which type is suitable for a non-owning link that breaks a shared_ptr ownership cycle?
- A. std::string
- B. std::weak_ptr
- C. std::unique_ptr
- D. std::vector
Show correct answer and explanation
Correct answer: B. std::weak_ptr
weak_ptr observes a shared object without contributing to shared ownership.
Q102. Why is shallow copying an owning raw pointer dangerous?
- A. It always duplicates the allocation
- B. It changes every integer to zero
- C. It disables destructors
- D. It can make multiple objects delete the same resource
Show correct 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.
Q103. What is the Rule of Zero in C++ class design?
- A. Prefer RAII members that avoid writing custom special member functions
- B. Declare no class members
- C. Use only static functions
- D. Avoid standard containers
Show correct 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.
Templates and Persistence
Q104. What is a class template?
- A. A compiler warning
- B. A serialized file
- C. A pattern for defining a family of classes
- D. A temporary runtime object only
Show correct answer and explanation
Correct answer: C. A pattern for defining a family of classes
Template arguments determine particular instantiations of the class pattern.
Q105. Which issue can make raw binary serialization nonportable?
- A. The existence of constructors
- B. Comments
- C. The use of local variables
- D. Differences in byte order and object representation
Show correct answer and explanation
Correct answer: D. Differences in byte order and object representation
Endianness, padding and type representation may differ across systems.
Error Handling
Q106. Which exception-safety guarantee promises that a failed operation leaves observable state unchanged?
- A. Basic guarantee
- B. Strong guarantee
- C. Only memory safety
- D. No guarantee
Show correct answer and explanation
Correct answer: B. Strong guarantee
The strong guarantee gives rollback-like behaviour on an operation’s failure.
Q107. How can polymorphic object slicing be avoided?
- A. Delete all virtual methods
- B. Disable inheritance
- C. Use references or pointers to base interfaces
- D. Copy derived objects by base value
Show correct answer and explanation
Correct answer: C. Use references or pointers to base interfaces
References and pointers preserve the object’s dynamic type.
Object Lifecycle
Q108. Which design choice most directly prevents a cyclic ownership leak between two std::shared_ptr-managed objects?
- A. Using std::weak_ptr for one non-owning link
- B. Calling push_back on both objects
- C. Using a larger vector capacity
- D. Making every field public
Show correct 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.
Additional Object-Oriented Programming MCQs — Questions 109–150
Q109. What does the C++ access specifier public permit?
- A. Access only from the class itself
- B. Access only through a friend
- C. No access from any function
- D. Access from permitted external code
Show correct answer and explanation
Correct answer: D. Access from permitted external code
Public class members are generally accessible through valid expressions from outside the class.
Q110. Which C++ expression creates an automatic local object of class Book?
- A. Book b;
- B. Book* b = nullptr;
- C. delete b;
- D. sizeof(Book);
Show correct answer and explanation
Correct answer: A. Book b;
A declaration such as Book b creates a local object when Book is default-constructible.
Q111. What is an object’s invariant?
- A. A property that is always false
- B. A property expected to hold in its valid states
- C. The size of its source file
- D. Its compiler version
Show correct answer and explanation
Correct answer: B. A property expected to hold in its valid states
Class invariants describe relationships that valid object states preserve.
Q112. Why might a member be declared private?
- A. To require global variables
- B. To make the member an independent function
- C. To protect representation details behind an interface
- D. To forbid all constructors
Show correct answer and explanation
Correct answer: C. To protect representation details behind an interface
Private access enables controlled use of internal representation.
Q113. Which principle asks classes to have focused responsibilities?
- A. FIFO principle
- B. Pigeonhole principle
- C. Binary search rule
- D. Single responsibility principle
Show correct answer and explanation
Correct answer: D. Single responsibility principle
Focused responsibilities help reduce unrelated reasons for a class to change.
Q114. Why are virtual functions useful?
- A. They enable runtime dispatch through base interfaces
- B. They disable all inheritance
- C. They convert classes to templates
- D. They automatically prevent memory allocation
Show correct 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.
Q115. What is the purpose of a C++ initializer list in a constructor?
- A. Declare an unrelated namespace
- B. Initialize bases and data members
- C. Sort all arrays
- D. Catch all exceptions
Show correct answer and explanation
Correct answer: B. Initialize bases and data members
Member-initializer lists initialize subobjects before the constructor body.
Q116. Which expression normally accesses a member via a pointer to an object?
- A. p::value
- B. p#value
- C. p->value
- D. p.value when p is a pointer
Show correct answer and explanation
Correct answer: C. p->value
The arrow operator accesses a member through a pointer.
Q117. What does a C++ reference variable generally provide?
- A. A standalone file on disk
- B. An untyped memory allocator
- C. A compiler command
- D. An alias to another object
Show correct answer and explanation
Correct answer: D. An alias to another object
A reference denotes an existing object or function according to its type.
Q118. What does the override specifier prevent?
- A. Accidental failure to match a base virtual function
- B. All calls to the function
- C. Any use of a constructor
- D. Every runtime exception
Show correct 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.
Q119. What is dynamic binding?
- A. Fixing all variables at compile time
- B. Selecting an overridden operation at runtime
- C. Linking object files only
- D. Sorting dynamic arrays
Show correct answer and explanation
Correct answer: B. Selecting an overridden operation at runtime
Dynamic dispatch resolves virtual calls according to the runtime object type.
Q120. Which operation cannot be overloaded in C++?
- A. The equality operator ==
- B. The subscript operator []
- C. The scope resolution operator ::
- D. The addition operator + for user-defined types
Show correct answer and explanation
Correct answer: C. The scope resolution operator ::
C++ does not allow overloading the scope-resolution operator.
Q121. What does a default constructor allow when accessible and applicable?
- A. Mandatory deletion of an object
- B. Only copy initialization
- C. Creation of an abstract class instance
- D. Construction without explicit arguments
Show correct answer and explanation
Correct answer: D. Construction without explicit arguments
A default constructor can be invoked with no supplied arguments.
Q122. When should a destructor release resources?
- A. When the object owns resources that need cleanup
- B. Whenever a local variable is read
- C. Only when a loop ends
- D. After every assignment
Show correct answer and explanation
Correct answer: A. When the object owns resources that need cleanup
RAII ties the release of owned resources to object lifetime.
Q123. What can cause a memory leak with raw owning pointers?
- A. Calling a pure function
- B. Losing an allocated pointer without releasing its allocation
- C. Using a const reference
- D. Creating an automatic int
Show correct answer and explanation
Correct answer: B. Losing an allocated pointer without releasing its allocation
Unreleased allocations can remain inaccessible and consume memory.
Q124. What is the C++ rule of five concerned with?
- A. Five integer types
- B. Five standard algorithms
- C. Copying, moving and destruction for resource-owning classes
- D. Five kinds of loops
Show correct 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.
Q125. What is move semantics intended to support?
- A. Copying every byte twice
- B. Preventing all assignments
- C. Converting every pointer to a reference
- D. Transferring resources from a source object when permitted
Show correct answer and explanation
Correct answer: D. Transferring resources from a source object when permitted
Move operations can transfer ownership instead of expensive copying.
Q126. Which expression constructs a dynamically allocated Widget in C++?
- A. new Widget()
- B. delete Widget()
- C. Widget::new()
- D. sizeof Widget()
Show correct answer and explanation
Correct answer: A. new Widget()
A new-expression allocates storage and constructs an object.
Q127. What is the preferred owner for one dynamically allocated object in modern C++?
- A. A reference to destroyed memory
- B. std::unique_ptr
- C. A non-owning raw pointer only
- D. An unrelated global int
Show correct answer and explanation
Correct answer: B. std::unique_ptr
unique_ptr expresses exclusive ownership with automatic destruction.
Q128. What is an interface in object-oriented design?
- A. A file extension
- B. A sorting order only
- C. A set of operations exposed to clients
- D. The amount of RAM installed
Show correct answer and explanation
Correct answer: C. A set of operations exposed to clients
An interface defines available interactions without requiring knowledge of implementation details.
Q129. What is a key benefit of composition over unnecessary inheritance?
- A. It guarantees zero memory use
- B. It forbids multiple objects
- C. It makes virtual functions illegal
- D. It can reuse behavior without creating an is-a relationship
Show correct 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.
Q130. What is dependency injection?
- A. Providing collaborators to an object from outside
- B. Deleting all inherited members
- C. Changing every variable to static
- D. A syntax error
Show correct answer and explanation
Correct answer: A. Providing collaborators to an object from outside
External collaborators make dependencies explicit and easier to substitute in tests.
Q131. What does const correctness help express?
- A. That every object is global
- B. Which operations should not modify an object
- C. That the program cannot throw
- D. That all members are public
Show correct answer and explanation
Correct answer: B. Which operations should not modify an object
Const qualifiers communicate and help enforce nonmodifying access.
Q132. When an exception is thrown, what is stack unwinding?
- A. Sorting the call stack
- B. Deleting every source file
- C. Destroying completed automatic objects as scopes are exited
- D. Restarting compilation
Show correct answer and explanation
Correct answer: C. Destroying completed automatic objects as scopes are exited
Unwinding leaves active scopes while destructors perform cleanup.
Q133. Which standard container offers key-value mappings with ordered keys?
- A. std::vector
- B. std::stack
- C. std::queue
- D. std::map
Show correct answer and explanation
Correct answer: D. std::map
std::map maintains an ordered associative mapping.
Q134. Which standard container supports average constant-time key lookup under typical hashing assumptions?
- A. std::unordered_map
- B. std::list
- C. std::forward_list
- D. std::priority_queue
Show correct answer and explanation
Correct answer: A. std::unordered_map
Hash-based unordered maps have average constant-time search under suitable hashing.
Q135. What is a template specialization?
- A. A virtual base
- B. A customized template definition for particular arguments
- C. An automatically deleted constructor
- D. An exception handler
Show correct answer and explanation
Correct answer: B. A customized template definition for particular arguments
Specialization can provide behavior for selected template arguments.
Q136. What is a lambda expression in modern C++?
- A. A class access specifier
- B. An operating-system process
- C. A way to define a function object inline
- D. A file opening mode
Show correct answer and explanation
Correct answer: C. A way to define a function object inline
A lambda creates a callable closure object.
Q137. What is a virtual destructor particularly important for?
- A. Calling only static member functions
- B. Allocating local integers
- C. Sorting a vector
- D. Deleting derived objects through base pointers
Show correct answer and explanation
Correct answer: D. Deleting derived objects through base pointers
A virtual base destructor ensures complete polymorphic destruction.
Q138. What is a copy constructor expected to initialize?
- A. A new object using another object
- B. The base class’s source code
- C. A file only
- D. An already existing object via assignment
Show correct answer and explanation
Correct answer: A. A new object using another object
Copy construction creates a distinct object from a source object.
Q139. What does operator= typically do for an existing object?
- A. Create a fresh type
- B. Assign a new state to the existing object
- C. Construct a completely unrelated file
- D. Always destroy the program
Show correct answer and explanation
Correct answer: B. Assign a new state to the existing object
The assignment operator updates an already constructed object.
Q140. What is the purpose of unit testing a class?
- A. Make every method virtual
- B. Eliminate all future bugs
- C. Verify individual methods and object behavior
- D. Set monitor brightness
Show correct answer and explanation
Correct answer: C. Verify individual methods and object behavior
Unit tests exercise defined class behavior against expectations.
Q141. Which SOLID guideline favors adding behavior without editing stable existing code?
- A. Least-recently-used principle
- B. Handshaking lemma
- C. Binary heap property
- D. Open-closed principle
Show correct answer and explanation
Correct answer: D. Open-closed principle
The open-closed principle encourages extension while limiting modification.
Q142. What is a covariant return type permitted in certain C++ overrides?
- A. A pointer or reference to a more-derived class type
- B. An arbitrary unrelated integer
- C. A return type always changed to void
- D. A parameter pack
Show correct 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.
Q143. Can constructors in C++ themselves be virtual?
- A. Only as templates
- B. No
- C. Yes, always
- D. Only when private
Show correct answer and explanation
Correct answer: B. No
Construction establishes dynamic type, and C++ constructors cannot be virtual.
Q144. What does the nullptr literal represent in C++?
- A. A string terminator object
- B. A valid object address in every case
- C. A null pointer value
- D. An integer with value one
Show correct answer and explanation
Correct answer: C. A null pointer value
nullptr is the dedicated null pointer literal.
Q145. What is the benefit of using an enum class over an unscoped enum?
- A. Automatic deep copying of all objects
- B. Elimination of all casting
- C. A guarantee of memory-free code
- D. Stronger scoping and type safety
Show correct answer and explanation
Correct answer: D. Stronger scoping and type safety
Scoped enumerations limit unintended name and implicit conversion conflicts.
Q146. What is an object’s dynamic type in a polymorphic hierarchy?
- A. The type of the actual most-derived object
- B. Always the declared pointer type
- C. The compiler version
- D. The data-member count
Show correct 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.
Q147. Which design pattern creates objects through an interface rather than exposing construction details?
- A. Binary search
- B. Factory method
- C. Insertion sort
- D. Pigeonhole principle
Show correct answer and explanation
Correct answer: B. Factory method
A factory method delegates object creation through an abstraction.
Q148. Why use a virtual function’s base interface rather than downcasting routinely?
- A. To ensure every pointer is null
- B. To force code duplication
- C. To reduce dependence on concrete derived types
- D. To disable inheritance
Show correct answer and explanation
Correct answer: C. To reduce dependence on concrete derived types
Working through a base abstraction improves substitutability and decoupling.
Q149. What does std::make_unique<T>() typically return?
- A. A borrowed raw array
- B. A std::weak_ptr<T>
- C. An int containing the object size
- D. A std::unique_ptr<T> owning a newly created T
Show correct 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.
Q150. What does a const reference parameter often help avoid?
- A. Unnecessary copying of the passed object
- B. All function calls
- C. All access checking
- D. Every possible compiler error
Show correct answer and explanation
Correct answer: A. Unnecessary copying of the passed object
Passing by const reference allows read-only access without copying large objects.
Interactive MCQ Practice
Practise one MCQ at a time. Reveal the correct answer and explanation before proceeding to the next question.
Start Object Oriented Programming — One Question at a Time
