Template class problem

What is wrong with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace 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;
}
Last edited on
http://en.cppreference.com/w/cpp/language/data_members (member initialization)
Through a brace-or-equal initializer
you cannot use parenthesis (I suppose that the compiler thinks you are trying to declare a member function)


> here is the problem
"the problem" is not descriptive at all
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?!
Last edited on
> But if I avoid parenthesis, it works
1
2
A<int> ss{420};
A<int> ss = 420;
would both work, sorry if I wasn't clear.


> But how can I pass arguments to the template class object
¿are you asking about initialization lists?
http://en.cppreference.com/w/cpp/language/initializer_list

> 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.

Please explain if you are kind enough.
> 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
Thanks a lot! I learnt side of C++ which was new to me.
May God bless you...
Topic archived. No new replies allowed.