C++ | Misc C++ | Question 3

Predict the output of following C++ program

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
union A {
  int a;
  unsigned int b;
  A() { a = 10; }
  unsigned int getb() {return b;}
};
  
int main()
{
    A obj;
    cout << obj.getb();
    return 0;
}

chevron_right


(A) Compiler Error: union can’t have functions
(B) Compiler Error: can’t access private members of A
(C) 10
(D) garbage value


Answer: (C)

Explanation: Like struct and class, union can have methods. Like struct and unlike class, members of union are public by default.

Since data members of union share memory, the value of b becomes same as a.

Quiz of this Question



GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.