Could you please check out this piece of code:
#include <vector>
class A
{
public:
A(int a, int b);
};
class C :public A
{
public:
C(int a, int b):A(a,b){}
static C instances;
};
C C::instances;
int main()
{
return 1;
}
The compilation gives me error as:
$ c++ inheritance.cpp inheritance.cpp:16:6: error: no matching function for call to ‘C::C()’ inheritance.cpp:16:6: note: candidates are: inheritance.cpp:12:2: note: C::C(int, int) inheritance.cpp:12:2: note: candidate expects 2 arguments, 0 provided inheritance.cpp:8:7: note: C::C(const C&) inheritance.cpp:8:7: note: candidate expects 1 argument, 0 provided
I need C to inherit from A and I need A to have arguments in its constructor.
Finally, I need the instance’s static variable to be declared and defined with no arguments.
So is there a solution to that? I value your kind comments.
Another point to note:
if the static variable was a container, like:
static std::vector instances;
the code would compile just fine. Why?
EDIT:
Thanks for all the answers,
but, if I modify C C::instances; to C C::instances(0,0); i will get another error:
$ c++ inheritance.cpp
/tmp/cctw6l67.o: In function C::C(int, int)':A::A(int, int)’
inheritance.cpp:(.text._ZN1CC2Eii[_ZN1CC5Eii]+0x1b): undefined reference to
collect2: ld returned 1 exit status
any idea why? and how to fix it?
thanks
If you define a constructor, the compiler no longer generates a default one for you, which you attempt to call with
C C::instances;. You can bypass this by calling the available constructor:or provide a default constructor for
C.With
it compiles because no elements are created, and
std::vectorhas a default constructor which initializes an empty vector. Butwouldn’t compile.