0
class Base{
protected:
    int remainItems = 0;
public:
    Base(){}
    virtual int numOfItem() = 0;
};
class Deveried1 : public Base{
public: 
    Deveried1() :Base(){ remainItems = numOfItem(); }
    int numOfItem(){
        return 5;
    }
};
class Deveried2 : public Base{
public:
    Deveried2() :Base(){ remainItems = numOfItem(); }
    int numOfItem(){
        return 10;
    }
};
class Deveried3 : public Base{
public:
    Deveried3() :Base(){ remainItems = numOfItem(); }
    int numOfItem(){
        return 10;
    }
};
int main(){
    Base* foo = new Deveried3;
}

With this design, for every deveried class, I must do the same thing in constructor to initalize remainItems. I'd like to know if there are some better way/pattern in this situation.

user2477
  • 896
  • 2
  • 10
  • 23

3 Answers3

2

Indeed, you can't call derived class functions from the base class constructor, so this kind of twisted inversion of dependencies can't work. I'd pass the value to the base-class constructor:

Base(int numOfItems) : remainItems(nomOfItems) {}
Derived1() : Base(5) {}
Derived2() : Base(10) {}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

I do not see any benefit in the method, so I removed it and added an option to pass the variable in the base class constructor:

class Base{
protected:
    int remainItems;
public:
    Base(remainItems = 0) { this->remainItems = remainItems; }
};

class Deveried1 : public Base{
public: 
    Deveried1() :Base(5){}
    }
};

class Deveried2 : public Base{
public:
    Deveried2() :Base(10){}
    }
};

class Deveried3 : public Base{
public:
    Deveried3() :Base(10){}
    }
};

int main(){
    Base* foo = new Deveried3;
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Because polymorphism is only applied to methods, not variable. So "numOfItem()" is used instead const numOfItem – user2477 Dec 13 '14 at 11:49
  • @user2477 I don't think I understand your comment. Does your code allow anything this code would not? – nvoigt Dec 13 '14 at 11:53
  • Your code is correctly (only with my sample code). I just explain why i use numOfItem() instead of a magic number (benefit for readability), numOfItem is used in many places, not only in constructor. – user2477 Dec 13 '14 at 11:58
0

I believe what you're looking for is called the Non-Virtual Interface pattern.

How to implement an interface class using the non-virtual interface idiom in C++?

Community
  • 1
  • 1
Nard
  • 1,006
  • 7
  • 8