Both paragraphs, 7.3.3.p1 and p3, in the C++11 Standard, make reference to a using-declaration naming a constructor. Why is this necessary? The code below shows that the base class A
's constructors are seen in the derived class B
as expected.
class A
{
int i;
public:
A() : i(0) {}
A(int i) : i(i) {}
};
class B : public A
{
public:
// using A::A;
A f1() { return A(); }
A f2() { return A(1); }
};
int main()
{
B b;
A a1 = b.f1();
A a2 = b.f2();
}
If I comment out using A::A;
above nothing changes in the program execution.
That's meant for inheriting the non-default constructors from the parent class, which is A(int i)
in this case. Change your declaration in main like so:
int main()
{
B b(42); // Want to forward this to A::A(int)
...
}
Without the using A::A
clause, you'll get the following compiler error (at least from g++ 4.8.0):
co.cpp: In function ‘int main()’:
co.cpp:20:11: error: no matching function for call to ‘B::B(int)’
B b(42);
^
co.cpp:20:11: note: candidates are:
co.cpp:10:7: note: B::B()
class B : public A
^
co.cpp:10:7: note: candidate expects 0 arguments, 1 provided
co.cpp:10:7: note: constexpr B::B(const B&)
co.cpp:10:7: note: no known conversion for argument 1 from ‘int’ to ‘const B&’
co.cpp:10:7: note: constexpr B::B(B&&)
co.cpp:10:7: note: no known conversion for argument 1 from ‘int’ to ‘B&&’
but if you add the using A::A
declaration back, it compiles cleanly. b(42)
ends up calling A::A(int i)
.