Issue with C++ constructor -
edit: question came , think aced it! go stackoverflow!! :d
i have exams coming up, , 1 of questions on last year's exams spot problem implementation of following constructor , write corrected one.
rectangle::rectangle(string col, int len, int br) { setcolour(col); length =len; breadth=br; }
the class definitions follows:
class polygon { public: polygon(string col="red"); void printdetails(); // prints colour virtual double getarea()=0; void setcolour(string col); private: string colour; }; class rectangle : public polygon { public: rectangle(string, int, int); void printdetails(); // prints colour , area // part 3, delete line below double getarea(); private: int length; int breadth; };
i've written code compiler , runs fine. i'm guessing question relating inheritance, since string colour;
private, setcolour
public cant figure out. unless rectangle::rectangle(string col, int len, int br):length(len), breadth(br)
, set colour inside construcor or something.
its worth 3 marks not big deal if nobody wants answer, figure if i'm going have career programmer, in interest know as possible. ;)
thanks help.
ps, see getarea()
in rectangle
. when remove tells me "cannot instantiate abstract class". mean?
edit: here's main:
void main (void) { rectangle rect1 ("blue",5,6); rectangle *prect2 = new rectangle("red",5,6); rect1.setcolour("red"); rect1.printdetails(); prect2->printdetails(); }
i don't see wrong, though make more efficient using initialization list (otherwise private members of both classes initialized twice):
rectangle::rectangle(string col, int len, int br) : polygon(col), length(len), breadth(br) { }
notice initialization list can call constructor of polygon well.
see why should prefer use member initialization list? complete description of advantages of using initialization lists.
Comments
Post a Comment