We have a template class containing another class containing template object with parameterized constructor.
template<class T>
class A {
public:
class B {
public:
T object;
B(T obj) {
this->object = obj;
}
};
T foo(T obj) {
B *b = new B(obj);
return b->object;
}
};
Also we have a class of object we want as foo() parameter:
class Item {
public:
int value;
// Item() {}
// Non-parameter constructor. Within works fine
Item(int value) {
this->value = value;
}
};
Notice: Within non-parameter constructor
Item() {}
code run flawlessly, but for some reason constructor always runs once without being called explicitly.
And here goes main()
to call a.foo()
:
A<Item> a;
Item item(5);
cout << a.foo(item).value; //expected: 5
Eventually we got an error like this:
error: no matching function for call to 'Item::Item()'
B(T obj) {
^
Question: How to made code with this structure work without having non-parameter constructor in
Class Item {}
?
- What is the reason of that structure?
- I code implementation of doubly linked list and simplified such error from it into this code above.
HINT: I want to make code work without changing
Class Item {}
definition because I'm provider ofClass A
and I want to resolve this case particularly.
SOLVED
Error solved by using member initialization list. Thanks to Ulrich Eckhardt.
B(T obj) {
this->object = obj;
}
//wrong
B(T obj): object(obj) {}
//correct