#include <iostream>
usingnamespace std;
template <typename X>
class A {
X a;
public:
A(X var) { a = var; }
};
class B{
A<int> sss(420); // here is the problem
};
int main()
{
A<int> ob(5); // but this okay!
return 0;
}
The compiler says- "error: expected identifier before numeric constant" for that line.
But if I avoid parenthesis, it works. But how can I pass arguments to the template class object and how is this possible when there is no matching constructor to call?!
> and how is this possible when there is no matching constructor to call?!
I don't understand your question.
If you try to instantiate the object with a constructor that doesn't exist, it would not compile.
The following also works inside class B, here no argument is passed: A<int> ss;
But, if I write the same statement inside main function, it results in an error saying- "no matching function for to call 'A<int>::A()'"!
This is actually my question. My intuition suggests that there should also be an error inside class B for that statement as there is no version of constructor for class A that takes no argument.
> The following also works inside class B, here no argument is passed:
> A<int> ss;
if you put that in `main()' you are constructing an object using the default constructor.
However, if that is inside class B, is just a declaration. You are saying that `class B' has a member `ss' of type `A<int>', but you are not constructing it yet.
You will construct it with the initialization list
1 2 3 4 5
class B{
A<int> sss;
public:
B(): sss(42) /*calling the constructor for the members*/ {}
};
1 2 3 4 5 6
class B{
A<int> foo{}; //trying to construct with the default constructor
A<int> bar;
public:
B(){} //not calling any constructor, `bar' would use the default
};
would fail because A<int> does not have a default constructor