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;
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();
};
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Dec, 2016
Like Article
Save Article