Output of C++ Program | Set 9
Predict the output of following C++ programs.
Question 1
template < class S, class T> class Pair { private : S x; T y; /* ... */ }; template < class S> class Element { private : S x; /* ... */ }; int main () { Pair <Element< int >, Element< char >> p; return 0; } |
chevron_right
filter_none
Output:
Compiler Error: '>>' should be '> >' within a nested template argument list
When we use nested templates in our program, we must put a space between two closing angular brackets, otherwise it conflicts with operator >>. For example, following program compiles fine.
template < class S, class T> class Pair { private : S x; T y; /* ... */ }; template < class S> class Element { private : S x; /* ... */ }; int main () { Pair <Element< int >, Element< char > > p; // note the space between '>' and '>' return 0; } |
chevron_right
filter_none
Question 2
#include<iostream> using namespace std; class Test { private : static int count; public : static Test& fun(); }; int Test::count = 0; Test& Test::fun() { Test::count++; cout<<Test::count<< " " ; return * this ; } int main() { Test t; t.fun().fun().fun().fun(); return 0; } |
chevron_right
filter_none
Output:
Compiler Error: 'this' is unavailable for static member functions
this pointer is not available to static member methods in C++, as static methods can be called using class name also. Similarly in Java, static member methods cannot access this and super (super is for base or parent class).
If we make fun() non-static in the above program, then the program works fine.
#include<iostream> using namespace std; class Test { private : static int count; public : Test& fun(); // fun() is non-static now }; int Test::count = 0; Test& Test::fun() { Test::count++; cout<<Test::count<< " " ; return * this ; } int main() { Test t; t.fun().fun().fun().fun(); return 0; } |
chevron_right
filter_none
Output:
Output: 1 2 3 4
Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.
Recommended Posts:
- Output of C Program | Set 23
- Output of C++ Program | Set 10
- Output of C Program | Set 22
- Output of C++ Program | Set 8
- Output of C++ Program | Set 7
- Output of C Program | Set 21
- Output of C++ Program | Set 6
- Output of C Program | Set 24
- Output of C++ Program | Set 18
- Output of C++ Program | Set 17
- Output of C++ Program | Set 16
- Output of C++ Program | Set 15
- Output of C++ Program | Set 14
- Output of C++ Program | Set 13
- Output of C++ Program | Set 12