Polymorphism Code Review

Posts: 1
Joined: Mon May 14, 2018 7:41 am

Polymorphism Code Review

Postby speedcuber92 » Tue May 15, 2018 9:35 am

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.


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.

Posts: 10
Joined: Sun Oct 08, 2017 4:26 pm

Re: Polymorphism Code Review

Postby jeanleflambeur » Sun May 20, 2018 9:03 am

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
    //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;

Who is online

Users browsing this forum: No registered users and 8 guests