Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ | Misc C++ | Question 3

Improve Article
Save Article
  • Last Updated : 28 Jun, 2021
Improve Article
Save Article

Predict the output of following C++ program

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;

(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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!