ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Logger {
public:
static int instances;
Logger() { instances++; }
~Logger() { instances--; }
};
int Logger::instances = 0;
void createTemp() {
Logger temp;
cout << Logger::instances << " ";
}
int main() {
Logger l1;
createTemp();
cout << Logger::instances;
}- A. 2 1
- B. 1 1
- C. 2 2
- D. 1 2
Correct answer: A. 2 1
l1 is constructed first: instances=1. createTemp() constructs its own local temp, bumping instances to 2, printed inside the function ("2 "); when createTemp() returns, temp goes out of scope and its destructor runs, decrementing back to 1, which main then prints ("1").
More OOP with C++ and Java questions
- What is printed? cpp struct Event { virtual void handle() const { cout << "generic-event "; } }; struct ClickEvent : Event { void handle()…
- A lambda expression captures a local variable from its enclosing method. What restriction does Java place on that variable?
- In Java, instance method calls (non-static, non-private, non-final) use dynamic dispatch based on the object's actual run-time class…
- What is printed? cpp struct Vec2 { int x, y; Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; } }; int main() { Vec2 a{1…
- A base class has a non-virtual destructor. A derived class owns a dynamically allocated member that it frees in its own destructor. What…
- java interface Greet { default String hello() { return "Hi"; } } class English implements Greet {} class French implements Greet { public…