Search code examples
c++dynamic-memory-allocation

error while extending an array: no operator found which takes


I want to extend my array by one when i call the addBranch function, and then add the new Branch object to the that extended empty area, and I am trying to prevent my code from memory leak. I thought i was doing right but i am stuck with this function.

it gives me error "binary '=' : no operator found which takes a right-hand operand of type 'Branch *' (or there is no acceptable conversion)". I need some help here assigning the last element to a new Branch object that won't be deleted after extermination of function. I am just new to C++, so there might be some big mistakes. I am not allowed to use vectors etc.

  // ------- Adds a branch to system -------- //
    void BankingSystem::addBranch(const int id, const string name){
        if(isBranchExisting(id)){
            cout << "\n\tBranch " << id << " already exists. Please try it with another id number.";
        }
        else if(!isBranchExisting(id)){
            Branch* tempArray = new Branch[cntAccounts];
            for(int i = 0; i<cntAccounts; i++){
                tempArray[i] = allBranches[i];
            }

            delete[] allBranches;

            allBranches = new Branch[cntAccounts+1];
            for(int i = 0; i<cntAccounts; i++){
                allBranches[i] = tempArray[i];
            }
            allBranches[cntAccounts] = new Branch(id, name);  // error at this line

        }
    }

Solution

  • As the error message says, you're trying to assign a pointer to an object. You (probably) want to assign an object instead:

    allBranches[cntAccounts] = Branch(id, name); // no "new"
    

    I would also suggest you use std::vector<Branch> rather than hand-forged arrays. This will fix the memory leak from forgetting to delete tempArray, or from something throwing an exception if you do add the missing delete[].

    Also, if you do use vector, then the whole dance can be replaced with

    allBranches.push_back(Branch(id, name));