Output of C++ Program | Set 7

Predict the output of following C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

class Test1 {
    int y;
};
  
class Test2 {
    int x;
    Test1 t1;
public:
    operator Test1() { return t1; }
    operator int() { return x; }
};
  
void fun ( int x)  { };
void fun ( Test1 t ) { };
  
int main() {
    Test2 t;
    fun(t);
    return 0;
}

chevron_right


Output: Compiler Error
There are two conversion operators defined in the Test2 class. So Test2 objects can automatically be converted to both int and Test1. Therefore, the function call fun(t) is ambiguous as there are two functions void fun(int ) and void fun(Test1 ), compiler has no way to decide which function to call. In general, conversion operators must be overloaded carefully as they may lead to ambiguity.

Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
class X {
private:
  static const int a = 76;
public:
  static int getA() { return a; }
};
  
int main() {
  cout <<X::getA()<<endl;
  return 0;
}

chevron_right


Output: The program compiles and prints 76
Generally, it is not allowed to initialize data members in C++ class declaration, but static const integral members are treated differently and can be initialized with declaration.

Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


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