mercredi 1 juillet 2015

method binding in C++

class Shape {
    public:
        virtual void draw() = 0;
        virtual void area() { . . .}
        . . .
};

class Circle : public Shape {
    public:
        void draw() { . . . }
        . . .
};

class Rectangle : public Shape {
    public:
        void draw() { . . . }
        . . .
};

class Square : public Rectangle {
    public:
        void draw() { . . . }
        . . .
};

Rectangle* r = new Rectangle;
r->draw(); // (1)

r = new Square;
r->draw(); // (2)

Shape* sh = new Circle;
sh->area(); // (3)

Square* sq = new Square;
sq->draw(); // (4)

(1),(2) dynamic binding, there's no doubt i think

(3) Since any class derived from Shape don't override the method area, it's resolved to Shape::area() by compiler?

(4) No class derived from Sqaure class, sq can only reference Square type, it means static method binding occurs?

Is there anything wrong?? thanks in advance.

Aucun commentaire:

Enregistrer un commentaire