Challenger App

No.1 PSC Learning App

★
★
★
★
★
1M+ Downloads
Predict the output #include using namespace std; class Test { public: int x; Test( ) { x = 10; } }; int main() { Test t1, t2; t1.x = 20; cout<

A10

B20

CGarbage Value

DCompilation Error

Answer:

A. 10

Read Explanation:

Object Initialization and Scope in C++

  • Class Structure: The code defines a class named Test with a public integer member variable x and a default constructor.
  • Constructor Execution: When Test t1, t2; is executed in the main function, two distinct objects of the Test class are created. The constructor Test() is called automatically for each object, initializing t1.x to 10 and t2.x to 10.
  • Independent Objects: In C++, each instance (object) of a class has its own copy of non-static member variables. Therefore, t1 and t2 occupy different memory locations and are entirely independent of each other.
  • Assignment Operation: The statement t1.x = 20; modifies the value of x only for the object t1. This assignment has no effect on the state of the object t2.
  • Final Output: Since t2.x was initialized to 10 by the constructor and never modified thereafter, the command cout << t2.x; will print the value 10 to the console.

Related Questions:

The symbols used in an assembly language are :
EBCIDIC is a _____ bit code.
Full Form for EBCDIC:
In programming, what is the purpose of a loop?
ഒരു പ്രോഗ്രാം താഴെപ്പറയുന്ന നിർദ്ദേശങ്ങൾ നടപ്പിലാക്കുന്നു. INPUT N IF N > 0 GOTO L1 PRINT "NEGATIVE" STOP L1: IF N < 100 GOTO L2 PRINT "LARGE" STOP L2: PRINT "SMALL POSITIVE" STOP N-ന്റെ ഇൻപുട്ട് മൂല്യം 120 ആണെങ്കിൽ, താഴെപ്പറയുന്നവയിൽ ഏത് പ്രസ്താവനയാണ് ശരി ?