揮発性のメモ2

http://d.hatena.ne.jp/iww/

コンストラクタの中から仮想関数は呼べない

#include <iostream>
using namespace std;


class hoge {
public:	
    int a;

    hoge(){ 
        cout << "hoge" << endl;
        init(); 
    }
    virtual void init(){
        a = 123;
    }
};

class piyo: public hoge {
public:	

/*  piyo(){ 
        cout << "hoge" << endl;
        init(); 
    } */
    virtual void init(){
        a = 456;
    }
};


int main() {
    hoge *n = new piyo();
    cout << n->a << endl;  // 123になる

    return 0;
}

コンストラクタ内では自分のクラスの関数しか呼べない。仮想関数を継承してても無視される。


コンストラクタ内で初期化関数を呼び出して、思った通りの関数が呼び出されないのはこれが原因。
コンストラクタは基底の方から順に全て呼ばれるので、派生クラスのコンストラクタに初期化関数を書いても ちょっと無駄が多そう


PHPと往復するときはよく混乱するので注意する


C++: What is A Pure Virtual FunctionPure Virtual Function - Programmer and Software Interview Questions and Answers
ロベールのC++教室 - 第17章 派生と構築2 -

ロベールのC++入門講座