Constructors and destructors are fundamental concepts in object-oriented programming, especially in C++. They play a crucial role in the initialization and cleanup of objects. Let's see how well you understand these concepts with this beginner-friendly quiz!
1. Which of the following is true about constructors in C++?
Answer:
Explanation:
Constructors have the same name as the class and are used to initialize object properties when an object is created.
2. How many constructors can a class have in C++?
Answer:
Explanation:
A class in C++ can have multiple constructors as long as they have different parameters. This is known as constructor overloading.
3. Which constructor gets automatically added to a class if we don't add any constructor?
Answer:
Explanation:
If no constructor is provided, the compiler automatically provides a default constructor.
4. What does the destructor do in C++?
Answer:
Explanation:
The destructor is called automatically when an object goes out of scope. It is used to release any resources (like memory) that the object might have acquired during its lifetime.
5. What is the name of the destructor for a class named Book?
Answer:
Explanation:
The destructor has the same name as the class but is preceded by a tilde ().
6. Which of the following statements is true?
Answer:
Explanation:
Constructors can be overloaded based on the number and/or type of parameters. Destructors don't have parameters and neither constructors nor destructors return values.
7. Which type of constructor is called when an object is created as a copy of another?
Answer:
Explanation:
The copy constructor initializes an object as a copy of another. It typically takes a reference to the same class as its parameter.
8. When is the destructor called?
Answer:
Explanation:
The destructor is called just before the object's memory is deallocated, i.e., when the object is about to be deleted.
9. Can destructors be overloaded in C++?
Answer:
Explanation:
Destructors cannot be overloaded. A class can have only one destructor.
10. Which of the following is the correct way to define a parameterized constructor for a class named Student that takes an integer age?
Answer:
Explanation:
The correct way to define a parameterized constructor is to give it the same name as the class and specify the parameters.
Comments
Post a Comment