mercredi 23 décembre 2015

C++ Initialize abstract base class protected member for all derived classes

Is it possible to initialize abstract base class' protected member for all derived objects without writing the same initializer list in all derived class constructors? So that it acts like a static member for all derived objects. I have this abstract base class:

A.h

class A {
public:
    A(string fileName);
    virtual ~A();
    virtual void open_file() = 0;
private:
    string fileName;
};

A.cpp

A::A(string fn) : fileName {fn} {} //Initializer list is written only once here
A::~A() {}

B.h

class B : public A {
public:
    B();
    ~B();

    void open_file() const override;
};

B.cpp

B::B() {} //No initializer list for A::fileName here
void B::open_file() const {
    ifstream SomeFile(fileName); //Use base class' protected member
    ..... //Do some stuff with open file
}

And imagine there's also a C derived class without an initializer list for A here that has a different overriden open_file function..

main.cpp

string fname = {"foo.txt"};
A* APtr = new B(fname); //This initializes A's fileName for all derived objects as "foo.txt"
Aptr->open_file(); //B opens foo.txt
fname = "bar.txt";
A* A2Ptr = new C(fname); //Now fileName that both B and C consume is changed to "bar.txt"
A2Ptr->open_file(); //C opens bar.txt
APtr->open_file(); //B now opens bar.txt

Aucun commentaire:

Enregistrer un commentaire