Output of C++ Program | Set 9

Predict the output of following C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

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


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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




Question 2



filter_none

edit
close

play_arrow

link
brightness_4
code

#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


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#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


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


Article Tags :

Be the First to upvote.


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