Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading