Search code examples
c++variablespolymorphismdata-members

Polymorphism and data members c++


I am having issues with polymorphism I have set these basic classes up methods will be added later but I want the different data members to be accessible from these class.

class square
{
public:
    bool canBeBought;
    string name;
};

class property : public square
{ 
public:
    int rent;
    int colour;
    int cost;
    bool bought;
};

class specialSquare : public square
{
private:

public:
};

Here is the code that I am calling

square* properties[23];
for(int i = 0; i < 23; i++)    
{
    if(propertyStrings.at(i).substr(0,8) == "Property")
    {
        istringstream ss(propertyStrings.at(i).substr(11,21));
        string temp;
        properties[i] = new property;
        while(!ss.eof())
        {
            properties[i]->bought = false;
            properties[i]->name = propertyStrings.at(i).substr(0,11);
            cout << "Name: " << properties[i]->name << endl;
            ss >> temp;
            properties[i]->cost = atoi(temp.c_str());
            cout << "Cost: "<< properties[i]->cost << endl;
            ss >> temp;
            properties[i]->rent = atoi(temp.c_str());
            cout << "Rent: "<< properties[i]->rent << endl;
            ss >> temp;
            properties[i]->colour = atoi(temp.c_str());
            cout << "Colour: "<< properties[i]->colour << endl << endl;

            break;
        }
    }
}

my issue is that because the name variable is in the square class it works fine but the data members for the property class don't get recognised. My aim was to try and get all square data stored in one array thats the property class and the specialSquare class as this would make things easier later on in my program.


Solution

  • I guess your problem is that the compiler doesn't recognize your "properties" pointers as pointing to instances of class Property, because you saved them as pointers to Square. Casting properties[i] to a pointer to class Property (((property*)properties[i])->colour) should do the trick (you're explicitly telling the compiler that this is, in fact, that class, and you have made sure that it cannot be another class).

    If Property and Special_Square are not, in fact, Squares, polymorphism may be the wrong choice here, though. There are other ways to accomplish the task, e.g. by an array of variants.