Home > Enterprise >  How to access a Protected Variable Correctly?
How to access a Protected Variable Correctly?

Time:12-02

I am trying to access one of the protected variable from items.h class using components.cpp class but I got the error confusing me: :D

Item::Quantity': cannot access forbidden protected member declared in class 'Item'

item.h

 protected:
        int32 Quantity;

component.h

#include "Items/Item.h"
Item* AddItem(class Item* Item, const int32 Quantity);

component.cpp

ItemAddResult Component::TryAddItem_Internal(class Item* Item)
{
    Items.Add(Item);
    return ItemAddResult::AddedAll(Item->Quantity);
}

CodePudding user response:

You can solve this by making the class Component a friend of class Item by adding a friend declaration inside class Item as shown below:

item.h

class Item{
    friend class Component;
    protected: 
        int32 Quantity;
    //other members here
}
  • Related