1

I'm working on a game, and I want to store the character belongs to a unit inside the class that defines the units. (as objects)

This is the defining class. (I use inheritance)

class Units
{
    public:
       char indicator;

        Units();
        virtual ~Units();
    protected:
    private:
};

Units::Units (){}
Units::~Units (){}


class WoodenBoxClass: public Units
{
    public:
        WoodenBoxClass.indicator = 'B';
};

During the compilation, when "WoodenBoxClass.indicator = 'B';" comes, I get an error message:

50|error: expected unqualified-id before '.' token

What should I do? The main question is that how can I reach that the "indicator" variable is the same to every "WoodenBoxClass" object?

1
  • there is no need to define empty constructor or destructor in c++. Commented Apr 25, 2013 at 14:26

2 Answers 2

2

You need to initialize member variables in the class constructor. There are two ways to do it:

  1. Simply assign to it in the child-class constructor

    WoodenBoxClass()
    {
        indicator = 'B';
    }
    
  2. Have a constructor in the base class that takes the indicator as argument, and use an initializer list in the child-class constructor:

    class Unit
    {
        ...
        explicit Unit(char ind) : indicator(ind) {}
        ...
    };
    
    class WoodenBoxClass : public Unit
    {
        ...
        WoodenBoxClass() : Unit('B') {}
        ...
    };
    
Sign up to request clarification or add additional context in comments.

1 Comment

The first version works. Thank you very much, especially for the quick answer! =)
0

To keep the "indicator" variable same to every "WoodenBoxClass" object, you can use static variable.

class WoodenBoxClass: public Units
{
    public:
        static char indicator = 'B';
};

class Units
{
    public:
       //char indicator;   //not necessary actually

        Units();
        virtual ~Units();
    protected:
    private:
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.