Home > Software engineering >  Using regular pointers on Polymorphism c
Using regular pointers on Polymorphism c

Time:02-04

I'm trying to learn Polymorphism in C , and the way I've been learning it was with raw pointers or smart pointers but then I've been trying to use regular pointers this time and I even tried to add the pointers to a vector from the constructor like this:

std::vector<bank_account*> bank_accounts; 

bank_account::bank_account(std::string Name, int Balance)
    : name{Name}, password{create_random_passowrd()}, balance{Balance}, Id{create_ID()} {}

saving_account::saving_account(std::string Name, int Balance, float Interest)
    : bank_account{Name, Balance}, interest_rate{Interest}{
        bank_account *ptr = this;
        bank_accounts.push_back(ptr);
    }

I did things this way because I would like to avoid doing "push.back" to add every object I create when calling the constructor(every attempt I did with smart pointers or raw pointers I always ended up calling the same constructor again and then creating an infinite loop) and also to achieve polymorphism without worrying about memory leaks in this situation, but I'm finding myself with some issues on using virtual functions and I think it might have something to do with this. I'd be really glad if you guys could tell if this is a good idea or not and also I'd like to say thanks for your attention!

CodePudding user response:

To your last comment, yes, those are two examples of different concerns. The main issue with this approach is that pointers are being put together in a vector, regardless of where actual account objects are constructed within the program, which may be entirely unrelated cases.

Therefore, the principle of separation of concerns implies that a bank account class should just model the relevant aspects of some type of bank account. If, for example, it will be used to represent a list of bank accounts associated with a client of a bank, then it should be the responsibility of a "client" object to manage that list. Now, I'm not sure what issues you encountered with smart pointers, but since I would recommend using them in the example I just gave, here is a snippet showing the correct usage:

#include "bank_account.h"
#include <memory>
#include <vector>

class Client
{
    using account_ptr = std::unique_ptr<bank_account>;
    std::vector<account_ptr> m_accounts;
    // ...
};

Different account types can be added with std::make_unique, available since C 14:

m_accounts.emplace_back(std::make_unique<bank_account>("A", 100));
m_accounts.emplace_back(std::make_unique<savings_account>("B", 2000, 0.5));
  •  Tags:  
  • Related