I am aware this is bad form and that default-values should be specified in the declaration, but if you would please indulge me for a moment.. why does this compile? and what is happening exactly?
#include <iostream>
using namespace std;
class test
{
public:
test(int n);
};
test::test(int n = 666)
{
cout << n;
}
int main()
{
test t;
cin.sync();
cin.ignore();
return 0;
}
Output: 666
.. how do templates affect the same piece of code?
template <class T>
class test
{
public:
test(int n);
};
template <class T>
test<T>::test(int n = 666)
{
cout << n;
}
int main()
{
test<int> t;
cin.sync();
cin.ignore();
return 0;
}
Error: no appropriate default constructor available
Thank you for your time!
It looks like the C++ specification specifically allows the first case and disallows the second!
Quote from the C++ spec (§8.3.6/4):
For non-template functions, default arguments can be added in later declarations of a function in the same scope.
So it looks like for non-template functions, you can indeed introduce the default arguments later on. No idea why this doesn't work for templates, though!