Search code examples
c++stackprivate-members

Accessing private members when implementing in a .cpp file


I'm trying to implement code for a .h file in a .cpp file. This is the header file:

class ProcessOrders
{
public: 
    double process_shipment(int q, double c);
    double process_order(int q);
private:
    std::stack<Inventory> Inventory_on_hand;    // keep track of inventory on hand
    std::stack<Order> orders_to_be_filled;      // keep track of orders
};

The problem is that the functions process_shipment and process_order require the ability to push things onto the private stacks, but I get an "unable to resolve identifier" error if I try to refer to them in the .cpp file.

This is probably really obvious, but how do I get access to the private members while implementing the public ones in the .cpp file? I can't modify the header file.


Solution

  • When you implement member functions outside of their class you need to prefix all member functions' names with ClassName::.

    Doing that enables you to just access every private variable with their respective name.

    Also do not forget to #include your header file of your class at the top of your .cpp file.

    double ProcessOrders::process_shipment(int q, double c)
    { /*...*/ Inventory_on_hand. //... }
    double ProcessOrders::process_order(int q)
    { /*...*/ }