Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
7 years, 2 months ago.
Error: No default constructor exists for class "mbed::DigitalOut"
Hi,
I have a problem using DigitalOut in my own class.
See my header and cpp file below:
lights.h
#ifndef lights_H #define lights_H #include "mbed.h" class Lights { public: Lights(PinName pIL, PinName pIR);// constructor ~Lights();// destructor private: DigitalOut do_indexLeft; DigitalOut do_indexRight; }; #endif
lights.cpp
#include "lights.h" Lights::Lights(PinName pIL, PinName pIR) : do_indexLeft(pIL), do_indexRight(pIR) {}
So I would like to initialize the DigitalOuts from my main() function by calling:
main.cpp
#include "lights.h" Lights lights(PTA1, PTB9);
The problem is that compiling the lights.cpp in web based IDE returns: Error: No default constructor exists for class "mbed::DigitalOut" in "lights.cpp", Line: 4, Col: 2
What can be the problem? I'm quite new for mbed and also used C++ a long time ago.
Thanks for your help in advance!
BR, Szilárd
2 Answers
6 years, 1 month ago.
Finally I can transform my answer in a comment to a real answer:
I slept a bit on this problem, and found that the problem is not in the cpp file, where the compiler complains, but in the header file:
DigitalOut do_indexLeft; // this variable declaration causes the error printout, as it would invoke the default constructor
The solution is using pointers:
DigitalOut* do_indexLeft;
Then creating the object in the constructor:
do_indexLeft = new DigitalOut(pIL);
Default constructor for classes like DigitalIn, DigitalOut, I2C, etc. (so where instantiating the class doesn't make sense without pin assignments) is not supported, and it is good as it is. Solution is instantiating these classes in the code only when the pins to be used are already decided.
Assigned to
6 years, 1 month ago.This means that the question has been accepted and is being worked on.
I slept a bit on this problem, and found that the problem is not in the cpp file, where the compiler complains, but in the header file:
The solution is using pointers:
Then creating the object in the constructor:
Hello Szilárd,
Both methods should work. I was not able to reproduce such error when testing your code. Using the online compiler the following
main.cpp
(plus a copy of your code with a defined destructor) compiled with no errors:Hi Zoltán,
Thanks for your comment!
In my original code I used declarations using the default constructor (without parameters). Maybe in actual version of mbed OS this is supported, but back then it was not. This is why I've modified my code to use pointers and dynamic allocation of these objects, which was a solution.
UPDATE: I've checked and default constructors are still not supported in newest release, so you probably used pointer version of my code?
BR, Szilárd
posted by Szilárd Greszler 23 Nov 2018