I am working with multiple classes and files, so I have created this dummy code to better define my problem. I have a parent class Parent and a child class Child. I've separated both of these in a .h and a .cpp file
parent.h
class Parent
{
Parent(int a, int b, int c);
protected:
void somefunc();
};
parent.cpp
#include<iostream>
#include "parent.h"
Parent::Parent(int a, int b, int c)
{
std::cout<<"Answer is: "<<a b c;
}
void Parent::somefunc()
{
std::cout << "I am some func";
}
child.h
#include "parent.h"
class Child : public Parent
{
public:
void funk();
};
child.cpp
#include"child.h"
void Child::funk()
{
somefunc();
}
And I'm using another file running.cpp to run this.
#include "child.h"
int main()
{
Child a;
a.funk();
return 0;
}
Trying to build this using g , gives me the error:
running.cpp: In function ‘int main()’:
running.cpp:4:11: error: use of deleted function ‘Child::Child()’
Child a;
^
In file included from running.cpp:1:0:
child.h:2:7: note: ‘Child::Child()’ is implicitly deleted because the default definition would be ill-formed:
class Child : public Parent
^~~~~
child.h:2:7: error: no matching function for call to ‘Parent::Parent()’
In file included from child.h:1:0,
from running.cpp:1:
parent.h:3:5: note: candidate: Parent::Parent(int, int, int)
Parent(int a, int b, int c);
^~~~~~
parent.h:3:5: note: candidate expects 3 arguments, 0 provided
parent.h:1:7: note: candidate: constexpr Parent::Parent(const Parent&)
class Parent
^~~~~~
parent.h:1:7: note: candidate expects 1 argument, 0 provided
parent.h:1:7: note: candidate: constexpr Parent::Parent(Parent&&)
parent.h:1:7: note: candidate expects 1 argument, 0 provided
The g command I'm using is g *.cpp -o test
I understand that I'm somehow supposed to give arguments to run the constructor of Parent, but I'm not sure how to do that.
- How do I get rid of this error?
- If the error is unrelated to this, how do I make an object of a Child Class when it is inheriting a class that has arguments in its constructor? I need to invoke the argument constructor as well, so I can't just make another blank constructor and use that instead.
CodePudding user response:
How do I get rid of this error?
You can solve this error by adding the default constructor in class Parent as shown below. Also, note that you need to make the constrcutors public.
parent.h
class Parent
{ public: //ADDED PUBLIC KEYWORD
Parent(int a, int b, int c);
//ADD DEFAULT CONSTRCUTOR
Parent()=default;
protected:
void somefunc();
};
