0

I am trying to derive class Smiley from Circle:

struct Smiley : Circle {
  void draw_lines() const;
};

void Smiley::draw_lines() const {
  Circle::draw_lines();   // outline
  /*rest of code here*/
}

This is the definition of Circle:

struct Circle : Shape {
  Circle(Point p, int rr);    // center and radius

  void draw_lines() const;

  Point center() const;

  void set_radius(int rr) { set_point(0, Point(center().x - rr, center().y - rr)); r = rr; }
  int radius() const { return r; }
private:
  int r;
};

I basically want a Circle with a couple arcs drawn on top. Theoretically, I should only have to write draw_lines() over (which is defined as virtual in Shape), but it does nothing without a constructor, and if I have a constructor, it get an error and says that Circle does not have a default constructor available, even if I have no code in the constructor relating to Circle.

Does anyone know why I am getting this error?

  • the error the compiler gives is self explanatory... – andrea.marangoni Dec 18 '13 at 18:33
  • But Circle does have a constructor, so why am I getting this error? I would just derive Smiley directly from Shape and redo the implementation details, but the assignment (not for class, just learning on my own) says to derive it from Circle. –  Dec 18 '13 at 18:36
  • @user2509848: It has a constructor, yes, and that constructor requires arguments. You're not giving it any. – Lightness Races in Orbit Dec 18 '13 at 18:39

2 Answers2

2

When you inherit from a class with no default constructor, you have to make sure you invoke the non-default one.

Otherwise your derived class tries to invoke that non-existent default constructor, as the error says. In this case, you can probably just pass the same arguments straight through.

struct Smiley : Circle {
  Smiley(Point p, int rr);
  void draw_lines() const;
};

Smiley::Smiley(Point p, int rr)
   : Circle(p, rr)
{};

I basically want a Circle with a couple arcs drawn on top

Then it's not a circle any more, so why does Smiley inherit Circle?

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
1

You've defined a constructor for circle that requires a Point and a Radius. You should define one with identical parameters for Smiley, that invokes the base class constructor with those parameters, via a Member Initialiser List.

struct Smiley : Circle {
  Smiley(Point p, int rr) : Circle(p, rr)
  {
  } 
  void draw_lines() const;
};
Community
  • 1
  • 1
Roddy
  • 64,903
  • 40
  • 160
  • 271