-1

So the problem is "Health" was not declared in this scope, I understand why and I think you understand what I want to do, I don't think it possible to do it with "if", is there another way?

thanks for your help

#include<iostream>

class Knight
{
    int health = 10;
};

class Mage
{
    int health = 8;
};


```
int main ()
{
    int player_class;
    std::cin >> player_class;

    if(player_class == 1) Knight player;
    if(player_class == 2) Mage player;

    std::cout << health;
}
  • 5
    Inherit the classes from a common base, then create `std::unique_ptr` outside of the if. `std::variant` could also work. – HolyBlackCat Oct 28 '20 at 07:11
  • 5
    [Get a good book or two](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), read about inheritance and *polymorphism*. – Some programmer dude Oct 28 '20 at 07:12
  • They are declarations of variables, not classes. There are two class definitions in your code, but no class declarations. – molbdnilo Oct 28 '20 at 07:29

1 Answers1

3

Yes, you can declare class object inside the if-statement but the scope of the declared object resides within the if-statement.

If you want at access it outside the if-statement, make a pointer and base class as follows,

#include <iostream>
#include <memory>    

class base {
        public:
            int health;
            base(int arg):health(arg){ } 
   virtual ~base(){ }       
};

class Knight : public base
{
    public:
          Knight():base(10){}
};

class Mage : public base
{
    public:
          Mage():base(8){}
};

int main ()
{
    int player_class;
    std::cin >> player_class;
    
   std::unique_ptr<base>  bPtr;

    if(player_class == 1) bPtr = std::make_unique<Knight>();
    if(player_class == 2) bPtr = std::make_unique<Mage>();

    std::cout << bPtr->health;
}
TruthSeeker
  • 1,539
  • 11
  • 24