I read a book about TDD using Java as an example, and I am writing in C ++. The problem was that in C ++ polymorphism is implemented a little differently. Here is an example:

class Dollar; class Money { public: static Dollar dollar(int amount); protected: int amount; }; class Dollar : public Money { public: Dollar(int amount); Dollar times(int value) const; bool operator==(const Dollar& dollar) const; }; 

Here the method Dollar dollar (int amount) needs to be changed to Money dollar (int amount). The book uses Java, so links are returned, and because of this, polymorphism works easily. In C ++, this code cannot be rewritten so literally. And how can this be done?

You can return a pointer, but then you have to forget to call delete. Use shared_ptr? I consider this possibility, but the abuse of shared_ptr leads to a slowdown due to synchronization.

What are the best practices for this situation?

Trying to do this:

 #include <memory> using std::shared_ptr; using std::make_shared; class Dollar; class Money { public: static shared_ptr<Money *> dollar(int amount); protected: int amount; }; class Dollar : public Money { public: Dollar(int amount); Dollar times(int value) const; bool operator==(const Dollar& dollar) const; }; shared_ptr<Money *> Money::dollar(int amount) { return make_shared<Dollar>(amount); } Dollar::Dollar(int amount) { this->amount = amount; } Dollar Dollar::times(int value) const { return Dollar(amount * value); } bool Dollar::operator==(const Dollar& dollar) const { return amount == dollar.amount; } 

but I get the error:

return: cannot convert "std :: shared_ptr" to "std :: shared_ptr"

    2 answers 2

    It is not clear what the problem is in the first example. This code is valid, the main definition of the function static Dollar dollar (...) write after the full definition of the class Dollar.

    In the shred_ptr example, replace shared_ptr<Money *> Money::dollar(int amount) with shared_ptr<Money> Money::dollar(int amount)

    UPD: If you have academic interest, then shared_ptr is fine. The default objects in Java are shared_ptr. If it is of practical interest, then the Dollar inheritance from Money is strange, as it is better to use template programming.

       class Dollar; class Money { public: Money(int amount):amount(amount){}; static Dollar dollar(int amount) protected: int amount; }; class Dollar : public Money { public: Dollar(int amount):Money(amount){} //Dollar times(int value) const; //bool operator==(const Dollar& dollar) const; }; Dollar Money::dollar(int amount) { return Dollar(amount); } int main() { Dollar d = Money::dollar(5); } 

      As you can see , everything works. It is not clear why Money uses Dollar (inheritance itself does not cause questions - the dollar is money :)).

      • The dollar function should return a dollar, but as a reference to Money. This is necessary so that the signature of the two methods dollar () and franc () is universal. - typemoon