简体   繁体   中英

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.

binding wise it seems to be true . But above code have memory leaks

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

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

Here in you are allocating memory to r pointer twice , but i can only free memory once, hance memory leak..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM