S
S
Sergey66613132015-11-29 15:30:05
Python
Sergey6661313, 2015-11-29 15:30:05

How to add a variable to an object of an already defined class in c++?

on the example of python (3):

class entity: pass   # обьявляем класс
player = entity()    # новый обьект player
player.dead = True   # ТУТ мы создаём новую переменную для player? не указанную в классе entity
print(player.dead)   # печатаем её (чисто для примера)

There such code works. The question is how to write the same only in c++?
#include <stdio.h>                 // библиотека с функии printf
class entity{};                    // обьявляем класс
int main(int argc, char* argv[] ){ // магия :)
  entity player;                   // создаём обьект player
  bool player.dead = true;         // ТУТ должна создаваться переменная, но ни судьба :(
  printf("%s", player.dead ? "true" : "false");// сдесь и далее  - более страшное колдунство чем int main :)
  return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mercury13, 2015-11-29
@Sergey6661313

Method 1. Inheritance.

class Entity
{
public:
  virtual ~Entity() {}    // для корректной работы динамических структур данных 
                          // наподобие менеджеров уровней; в нашем примере не нужно;
                          // в реальной игре потребуется
}

class Player : public Entity
{
public:
   bool isDead;
}

int main()
{
   Player player;
   player.isDead = true;
   return 0;
}

If someone gives an Entity, which is guaranteed to be a Player, then
Player& somePlayer = dynamic_cast<Player&>(someEntity);

Method 2. Composition
class Player
{
public:
   Entity entity;
   bool isDead;
}

Method 3. Dictionary. This is already in case when someone else's code is so monolithic that nothing can break it.
struct PlayerInfo
{
    bool isDead;
}

std::map<const Entity*, PlayerInfo> playerInfo;

If someone else's code is monolithic, and objects also move around in memory, then find out what will be the "value" of the object (for example, some kind of identifier).
typedef std::string PlayerId;
std::map<PlayerId, PlayerInfo> playerInfo;

If the code is monolithic, and you can’t invent a “name” or “value” for an object, then you can’t.

A
Anatoly Medvedev, 2015-11-29
@balamyt92

No way. Because:
YmE14ybtZbNlxm.jpg

O
OnYourLips, 2015-11-29
@OnYourLips

No way.
This is a feature of python, and it exists in a small number of other languages. For example ruby.
And I note that this feature is more of a minus than a plus.
Prototyping with it is faster, but it negatively affects long-term support.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question