Pendo826
Pendo826

Reputation: 1002

Not able to use function variables ? Error expression must have class type

Hey i want to use the function wolves variable in the storyline and im trying to do this :

"\nYou awake on a beach to the sound of"<< Wolves().name; " starving and blood hungry," 
        "\nThere is a Rock on the ground.  You pick it up";
        inventory.push_back("Rock");

But Wolves().name; there is an error as mentioned in the title. Why cant i do this?

Here is the code for the function Wolves:

void Wolves()
{
    string name = "Wolves";
    int health = 20;
    hitPoints() +1;
}

Upvotes: 0

Views: 132

Answers (3)

Nero
Nero

Reputation: 1285

You can't access variables defined in a function from outside the function in C++, but you can change it to a class:

class Wolves {
  public:
    string name;
    // ...

    Wolves(); // Constructor
    //...
}

To access it you can use

Wolves wolve;
wolve.name = "whateverName"; // or set it in the constructor
cout << wolve.name << endl;

Upvotes: 1

Goyatuzo
Goyatuzo

Reputation: 58

What you did in there is create local variables within the function. Once the function exits, they no longer exist. What you want to do is make a Wolves class and create public member variables to do what you want. For an example,

class Wolves {
    public:
        string name;
        int health;

        Wolves(string name, int a);
}

Then on the main function,

Wolves w("Bob", 20);
cout << "The name is: " << w.name << endl;

Will output "The name is: Bob"

void functions don't really do anything unless you pass the value in by reference. If you want to alter the object via void function, you should do something like

void Wolves(Wolves & wolfToChange)
{
    wolfToChange.name = "Bob";
}

and that will directly alter the object.

Upvotes: 1

Timo Geusch
Timo Geusch

Reputation: 24341

You declared "name" as a local variable in a function called Wolves(), but the code that you were referring to expects the function Wolves() to return an object that has an accessible member name. That is why the compiler is complaining.

The way you wrote the code suggests that Wolves should be a class or struct, not a function.

Upvotes: 0

Related Questions