Page 1 of 1

Polymorphism Code Review

Posted: Tue May 15, 2018 9:35 am
by speedcuber92
Hello all!
I am pretty new with esp32 an c++ in general and your input would be greately appreciated.
I have a chunk of code where the goal is to send strings of data using a connection that were first invoked.
For this nodemcu-32s was used.

https://gitlab.com/toniVarga/polymorphism

Can you please advise me is this the right way to do it or is there a better way, or correct way.
So basically there is base class MyComm with pure virtual function and BT and UART classes that inhert from MyComm.
In setup we chose where to send the strings based on connection in which the first byte was received.

Also could you please advise me on some tools for debugging and tracing stack or heap level and stuff like that.

Re: Polymorphism Code Review

Posted: Sun May 20, 2018 9:03 am
by jeanleflambeur
You got the basic usage of inheritance and virtual methods right. There is one nasty bug though - you forgot to make your destructor virtual in the base class (MyComms). This means that if you ever destroyed an object through a pointer to the base class, the correct destructor would not be called.

Code: Select all

class MyComm
{
  public:
    //MyComm(); //no need for a constructor
    virtual ~MyComm() = default; //cannot make this abstract
   virtual void println(String) = 0;
};
Another useful thing is to use override on all overriden methods:

Code: Select all

class BT: public MyComm
{
	...
    void println(String) override;
};
Like this the compiler will warn you if the method doesn't correspond with any virtual from the base class. This can happen because of misspelling or renaming the method in the base class. It's just good practice.

One other hint - unrelated to inheritance - is to make the parameter of println a const reference. This will avoid unnecessary copies and allocations which for an arduino are pretty significant.

Code: Select all

 virtual void println(const String&) = 0;

Re: Polymorphism Code Review

Posted: Wed Jun 20, 2018 2:05 pm
by speedcuber92
Thanks very much for explanations!