CPP Object-Oriented Programming Concepts 2 — Questions and Answers
Question 1: What is a constructor in OOP?
- A method that destroys an object
- A special method called automatically when an object is created (Correct answer)
- A static factory method
- A method that copies an object
Correct answer: A special method called automatically when an object is created
A constructor is a special method invoked automatically upon object creation to initialize its state.
Question 2: Which design concept is described as 'favoring composition over inheritance'?
- Using abstract classes exclusively
- Building complex behavior by combining simpler objects rather than extending class hierarchies (Correct answer)
- Inheriting from multiple base classes
- Using only static methods
Correct answer: Building complex behavior by combining simpler objects rather than extending class hierarchies
Favoring composition means assembling objects with desired behaviors rather than relying on deep inheritance chains, improving flexibility.
Question 3: What is a 'static' method in OOP?
- A method that cannot be overridden
- A method belonging to the class rather than any instance (Correct answer)
- A method with no parameters
- A method that always returns void
Correct answer: A method belonging to the class rather than any instance
Static methods belong to the class itself and can be called without creating an instance of the class.
Question 4: What is the role of the 'this' keyword in OOP languages?
- Refers to the parent class
- Refers to the current object instance (Correct answer)
- Creates a new object
- Refers to a static context
Correct answer: Refers to the current object instance
'this' is a reference to the current object instance, used to differentiate instance variables from local variables.
Question 5: What is the purpose of a destructor or finalizer in OOP?
- To initialize object state
- To copy an object
- To perform cleanup operations before an object is garbage collected or destroyed (Correct answer)
- To override inherited methods
Correct answer: To perform cleanup operations before an object is garbage collected or destroyed
Destructors/finalizers release resources like file handles or memory allocations when an object is about to be destroyed.
Question 6: In OOP, what does 'coupling' refer to?
- The number of methods in a class
- The degree of interdependence between software modules (Correct answer)
- The ability to hide implementation details
- The process of inheriting from a parent class
Correct answer: The degree of interdependence between software modules
Coupling measures how much one class depends on another; low coupling is preferred for maintainability and testability.
What is a constructor in OOP?