Friday, June 12, 2015

Can I call a virtual function from ctor in C++?


Yes, but be careful. Actually, never call a virtual function in ctor or dtor.
the answer form the author of C++

@http://hilite.me/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>

using namespace std;

class Shape {
public:
    virtual void draw() {
        cout << "draw a Shape." << endl;
    }
};

class Circle : public Shape {
public:
    void draw() {
        cout << "draw a Circle." << endl;
    }
};


class Base {
public:
    Base() {
        cout << "Base()" <<endl;

        f();
        
        Shape* shape = new Circle;
        shape->draw();
    }

    virtual void f() {
        cout << "Base::f()" << endl;
    }
};

class Derive : public Base {
public:
    Derive() {
        cout << "Derive()" << endl;
    }

    void f() {
        cout << "Derive::f()" << endl;
    }
};


int main()
{
    Base* b = new Derive;
    
    return 0;
}

Base::f()
draw a Circle.
Derive()

No comments: