mercredi 31 juillet 2019

What Is a Proper and Elegant Way to Overload Constructors in C++

I touched C++ a few years ago and am having to go back to it for a project I'm working on. I learned most of the basics but never really nailed down on how C++ wants you to implement its idea of classes.

I have experience in other languages like Java, Python, and C#.

One of the troubles I'm having is understanding how to overload constructors in C++ and how to properly do inheritance.

For example, say I have a class called Rect and a class called Square that inherits from Rect.

In Java...

public class Rect {
   protected double m_length, m_width;

   public Rect(double length, double width) {
      this.m_length = length;
      this.m_width = width;
   }

   public double Area()
   {
      return (this.m_length * this.m_width);
   }

}

public class Square extends Rect {
   private String m_label, m_owner;
   public Square(double side) {
      super(side, side);
      this.m_owner = "me";
      this.m_label = "square";
   }

   //Make the default a unit square
   public Square() {
      this(1.0);
      this.m_label = "unit square";
   }
}

However the same process in C++ just feels convoluted.

Headers:

class Rect
{
public:
   Rect(double length, double width) : _length(length), _width(width) { } 
   double Area();

protected:
   double _length, _width;
}

class Square : public Rect 
{
public:
   Square(double side) : 
   Rect(side, side), _owner("me"), _label("square") { }

   Square() : Rect(1.0, 1.0), _owner("me"), _label("unit square");

private:
   std::string _owner, _label;
}

I feel like I shouldn't have to write out Rect again. It just seems like an awful lot of rewriting, especially since in my project I'm working with matrices a lot and I want to have constructors to be able to extend each other like in Java to avoid rewriting lots of code.

I'm sure there's a way to do this properly, but I haven't see anyone really talk about this problem.

Aucun commentaire:

Enregistrer un commentaire