Radley
Radley

Reputation: 11

error : "object" was not declared in this scope

Can someone please tell me why I'm getting this error? error : firstpokemon was not declared in this scope. And is there another way to write it?

#include <iostream>
#include "Charmender.h"
#include "Bulbasaur.h"
#include "Game.h"
#include "Squirtle.h"

using namespace std;

int main()
{
 srand(time(0));
 Game game;
 int frstchoice = game.getstarterchoice();
    if(frstchoice == 1)
        Charmender firstpokemon;
    else if(frstchoice == 2)
        Bulbasaur firstpokemon;
    else if(frstchoice == 3)
        Squirtle firstpokemon;

cout << "You chose No." << frstchoice << endl;
cout << firstpokemon.getatk();
    return 0;
}

The error is at cout << firstpokemon.getatk();

Upvotes: 0

Views: 3175

Answers (3)

user4375224
user4375224

Reputation:

Your firstpokemon is a local variable as it is getting created within the if block. Being a local variable , you CANNOT use it in any other block , and hence when you try to cout<<firstpokemon; in the main function , the compiler flags an error as it is unknown to the compiler at that point in time.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254471

You have three separate variables called firstpokemon, each scoped within the branch of the if...else statement in which it's declared. They are not in the wider scope of main.

A variable can only have a single type. If you want a variable to refer to various polymorphic types (assuming a common base class), then you'll need a pointer or reference, and you'll typically need dynamic allocation:

std::unique_ptr<Pokemon> firstpokemon;
if(frstchoice == 1)
    firstpokemon.reset(new Charmender);
else if(frstchoice == 2)
    firstpokemon.reset(new Bulbasaur);
else if(frstchoice == 3)
    firstpokemon.reset(new Squirtle);

if (firstpokemon)
    cout << firstpokemon->getatk();
else
    cout << "Wrong choice\n";

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409196

Code inside if statements are in their own scoping block, so they are local inside that block only.

If your classes are inheriting from the same base class then you can use a pointer to the base class, and allocate the instances inside the if statements.

Upvotes: 1

Related Questions