Creating plugins

We will create a base class called RegularPolygon from which all of our plugins, including Triangle and Square, would inherit.

The source code of packages can be downloaded from GitHub (https://github.com/kbipin/Robot-Operating-System-Cookbook):

#ifndef PLUGINLIB_TUTORIALS__POLYGON_BASE_H_ 
#define PLUGINLIB_TUTORIALS__POLYGON_BASE_H_ 
 
namespace polygon_base 
{ 
  class RegularPolygon 
  { 
    public: 
      virtual void initialize(double side_length) = 0; 
      virtual double area() = 0; 
      virtual ~RegularPolygon(){} 
 
    protected: 
      RegularPolygon(){} 
  }; 
}; 
#endif 

We will create two RegularPolygon plugins; the first will be Triangle and the second will be Square: pluginlib_tutorials/include/pluginlib_tutorials/polygon_plugins.h.

    #ifndef PLUGINLIB_TUTORIALS__POLYGON_PLUGINS_H_
    #define PLUGINLIB_TUTORIALS__POLYGON_PLUGINS_H_
    
    #include <pluginlib_tutorials/polygon_base.h>
    #include <cmath>
    
    namespace polygon_plugins
    {
      class Triangle : public polygon_base::RegularPolygon
      {
        public:
          Triangle(){}
    
          void initialize(double side_length)
          {
            side_length_ = side_length;
          }
    
          double area()
          {
            return 0.5 * side_length_ * getHeight();
          }
    
          double getHeight()
          {
            return sqrt((side_length_ * side_length_) - ((side_length_ / 2) * (side_length_ / 2)));
          }
    
        private:
          double side_length_;
      };
    
      class Square : public polygon_base::RegularPolygon
      {
        public:
          Square(){}
    
          void initialize(double side_length)
          {
            side_length_ = side_length;
          }
    
          double area()
          {
            return side_length_ * side_length_;
          }
    
        private:
          double side_length_;
    
      };
    };
    #endif
  

The preceding code should be self-explanatory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.81.58