How to create derived class in c++ -
i'm confused on how deal inheritance in c++
i'd pass parameters on constructor. got run when create class without parameters.
this small program:
#include <iostream> using namespace std; // base class class shape { protected: int width, height; public: shape(int w, int h) { width = w; height = h; } void setdimensions(int w, int h) { width = w; height = h; } }; // new class rectangle based on shape class class rectangle: public shape { public: int getarea() { return (width * height); } };
when compile errors:
$ g++ inheritance.cpp -o inheritance -g -std=c++11 inheritance.cpp:44:13: error: no matching constructor initialization of 'rectangle' rectangle r(3, 4) ^ ~~~~ inheritance.cpp:33:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, 2 provided class rectangle: public shape { ^ inheritance.cpp:33:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, 2 provided inheritance.cpp:33:7: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, 2 provided
constructors aren't inherited shape
. you'll need provide constructor rectangle
, can take parameter signature:
rectangle(int w, int h) : shape(w,h) { }
Comments
Post a Comment