Open In App

Output of C++ Program | Set 7

Last Updated : 27 Dec, 2016
Improve
Improve
Like Article
Like
Save
Share
Report

Predict the output of following C++ programs.

Question 1




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;
}


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




#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;
}


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads