Why Obj.*A is out of scope?

Here is part of my class assign_obj, constructor and operator that I want to print the object.
When trying to compile operator I am getting error :

error: 'A' was not declared in this scope for(assign_obj::item anItem : obj.*A){

Why is that?
If I try obj.A instead, I get error for the forloop as C++ can not loop a pointer of dynamic array.

class assign_obj{
    private:
        
        struct item{
            char value;
            int count;
        };
        item * A; //pointer A pointing to something of type Item
        int size;
    public:
        assign_obj();
        assign_obj(std::string);
        friend std::ostream& operator<<(std::ostream & out, assign_obj & obj);
//Constructor
assign_obj::assign_obj(string aString){
    size = aString.size();
    A = new item[size];

    item myItem;
    for(int i = 0; i < size; i++){
        myItem = {(char)toupper(aString[i]), 1};
        A[i] = myItem;
    }
}

// Print operator
std::ostream& operator<<(std::ostream & out, assign_obj & obj){
    out <<"[ ";
    for(assign_obj::item anItem : obj.*A){
        out << anItem.value;
        out << ":";
        out << anItem.count;
        out << " ";
    }
    out <<"]";
    return out;
}

>Solution :

You can’t use a for loop that way for a dynamically allocated array. You can use a plain old for loop for your plain old array.

std::ostream& operator<<(std::ostream & out, assign_obj & obj){
    out <<"[ ";
    for (size_t i = 0; i < obj.size; i++) {
        out << obj.A[i].value << ":"
            << obj.A[i].count << " ";
    }
    out <<"]";
    return out;
}

Leave a Reply