I have a class A that I what to be instantiated only via A(int arg1) constructor and I have class B that derived from class A that I want to be instantiated only via B(int arg1, int arg2) constructor.
Here is example:
class A
{
public:
int i;
A(int arg1)
{
i= arg1;
}
};
class B : public A
{
int j;
B(int arg1, int arg2)
{
i= arg1;
j= arg2;
}
};
that produce error:
inheritance_default_constructor.cpp: In constructor ‘B::B(int, int)’:
inheritance_default_constructor.cpp:16:6: error: no matching function for call to ‘A::A()’
{
^
inheritance_default_constructor.cpp:16:6: note: candidates are:
inheritance_default_constructor.cpp:5:6: note: A::A(int)
A(int arg1)
I can fix it like this:
class A
{
public:
int i;
A(int arg1)
{
i= arg1;
}
};
class B : public A
{
int j;
B(int arg1, int arg2) : A(arg1)
{
j= arg2;
}
};
But what if I need the body of B(int arg1, int arg2) constructor to be not in .h file, but in .cpp file, is it possible?
UPDATE:
I was doing it wrong:
//inheritance_default_constructor.h
class A
{
public:
int i;
A(int arg1)
{
i= arg1;
}
};
class B : public A
{
int j;
B(int arg1, int arg2) : A(arg1);
};
//inheritance_default_constructor.cpp
#include "inheritance_default_constructor.h"
B::B(int arg1, int arg2) : A(arg1)
{
j= arg2;
}
int main()
{
return 0;
}
In file included from inheritance_default_constructor.cpp:1:0:
inheritance_default_constructor.h: In constructor ‘B::B(int, int)’:
inheritance_default_constructor.h:15:32: error: expected ‘{’ at end of input
B(int arg1, int arg2) : A(arg1);
^
inheritance_default_constructor.cpp: At global scope:
inheritance_default_constructor.cpp:3:1: error: redefinition of ‘B::B(int, int)’
B::B(int arg1, int arg2) : A(arg1)
^
In file included from inheritance_default_constructor.cpp:1:0:
inheritance_default_constructor.h:15:2: error: ‘B::B(int, int)’ previously defined here
B(int arg1, int arg2) : A(arg1);
B(int arg1, int arg2)constructor to be not in .h file, but in .cpp file, is it possible?. Yes, it is possible. Give it a try and post a question if you encounter any problems.A(int arg1)should be defined asA(int arg1) : i(arg1) {}. B should then beB(int arg1, int arg2) : A(arg1), j(arg2) {}.