Can you explain the output of below C++ program ?
Why is the output of the above program is
- 5 : 1 : 20
- 1 : 1 : 50
- 5 : 2 : 50
Let’s try to dissect this C++ program step by step
TEACHER T(5), M
The above initializes a teacher object T with values Tid = 5, TeachCode = 0 and TeacherCount = 0
This will initialize M with values Tid = 1 (default value assigned in the constructor) TeachCode = 0 and TeacherCount = 0 —————————- (A)
When we call the function T.subject() which basically has the below code
void Subject(int S = 20) { TeachCode++; TeacherCount += S; }
The function increments TeachCode by 1 to give it’s value TeachCode = 1 and TeacherCount+= S will give it’s value TeacherCount = 20 as it’s initial value is 0.
Hence the first call prints 5 : 1 : 20 ———————————– (1)
calling M.subject(50) will change the values of TeachCode and TeacherCount which is dependent on the value of S which is initialized with a value of 50 via the function argument. Now since Tid in this case is already 1 from equation (A) above, it prints the output 1 : 1 : 50 ———————————– (2)
First invocation of T.subject() already changed the values of Tid, TeachCode and TeacherCount as 5, 1 and 20 respectively.
Calling subject() again via T.subject(30) will again update the values as
Tid = 5 (which isn’t modified in the subject function).
Since TeachCode was 1 initially, TeachCode++ will change it’s value to 2
Also TeacherCount was = 20 due to the first invocation of T.subject();
hence calling T.subject(30) this time will add 30 to it’s initial value giving it’s new value of 20+30 = 50
Hence the final call to subject will print 5 : 2 : 50 ———————————– (3)
Hope this clearly explains the behavior