c++ - Passing arguments to a superclass constructor -


i'm getting derived classes, , i'm working on famous shape class. shape base class, have 3 derived classes: circle, rectangle, , square. square derived class of rectangle. think need pass arguments derived class constructors base class constructor, i'm not sure how this. want set dimensions shapes create them. here have base class , 1 derived class:

shape(double w = 0, double h = 0, double r = 0) {      width = w;      height = h;      radius = r; }   class rectangle : public shape {      public:      rectangle(double w, double h) : shape(double w, double h)      {          width = w;          height = h;      }                    double area();      void display();       }; 

am on right track here? i'm getting following compiler error: expected primary expression before "double", in each of derived constructors.

you have change shape(double w, double h) shape(w, h). calling base constructor here.

in addition, don't have set width , height in constructor body of derived class:

  rectangle(double w, double h) : shape(w, h)   {} 

is enough. because in initializer list shape(w, h) call constructor of base class (shape), set these values you.

when derived object created, following executed:

  1. memory shape set aside
  2. the appropriate base constructor called
  3. the initialization list initializes variables
  4. the body of constructor executes
  5. control returned caller

in example, shape subobject initialized shape(double w = 0, double h = 0, double r = 0). in process, members of base part (width, height, radius) initialized base constructor. after that, body of derived constructor executed, don't have change here since of them taken care of base constructor.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -