Skip to content
Related Articles

Related Articles

Improve Article

Output of C++ Program | Set 9

  • Difficulty Level : Medium
  • Last Updated : 27 Dec, 2016
Geek Week

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

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



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

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

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :