user966379 user966379 - 2 months ago 8
C++ Question

how template inheritance works?

template<typename T>
class A {
public:
A(const T &t )
{
std::cout << t;
}
};
class C :
public A<int>,
public A<char>
{

public:
C(char c) : A<char>(c) {}

};

void main()
{
C obj('c');

}


While compiling following program, compiler is giving following error.
no default constructor exists for class "A<int>"

what compiler does internally?

Answer

C has two base classes - A<int> and A<char>. You have specified the explicit call to the base class A<char> constructor but you have not specified anything for the base class A<int>. When a constructor is not explicitly used in the initializer-list, the compiler tries to call the default constructor. Hence,

C(char c) : A<char>(c) {}

is equivalent to:

C(char c) : A<char>(c), A<int>() {}

That is a problem since A does not define a default constructor. You can use

C(char c) : A<char>(c), A<int>(0) {}

to resolve the problem.

Comments