0

I have a problem with my program... I have a class A, and class B and C that inherit from class A... they live inside another class called Game, like this:

class Game {
    public:
        Game(bool something);
       //all the other functions
    private:
      A a;
}

I do it like this because I don't know beforehand if the object will be a class B or C, so I declare it like A and then:

Game(bool something) {
    if (something) { a = B(); }
    else (something) { a = C(); }
}

Now my problem: In the program I ask weather 'a' is B or C... and I want that if its B, run a function than only B has and neither A nor C have. But, of course, the compiler don´t let me do it because it thinks a is a class A object. Does anybody knows how to fix this?

J Agustin Barrachina
  • 3,501
  • 1
  • 32
  • 52

2 Answers2

2
class Game {
    public:
        Game(bool something) : a() {};
        ~Game(){ if(a) delete a; };
        // this is only example, and really need to implement 3 or 5 method
        // or use std::shared_ptr instead of pointer, more details at
        // https://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29
    private:
      A* a;
}

Game(bool something) {
    if (something) { a = new B(); }
    else           { a = new C(); }
}

B* b= dynamic_cast<B*>(a);
if( b ) b->method_b_only();
C* b= dynamic_cast<C*>(a);
if( c ) c->method_c_only();

Possible special object name or id to define a type manually:

class B : public A {
  public:
    B() : _name("B") {}
    const std::string& name() { return _name; }
  private:
    std:string _name;
}

B* b = a;
if( "B" == b.name() ) b->method_b_only();
C* C = a;
if( "C" == c.name() ) c->method_c_only();
oklas
  • 7,935
  • 2
  • 26
  • 42
0

The most straightforward way to achieve the functionality you want is to use pointers. ie.

class Game {
    public:
        Game(bool something);
    private:
        A *a;
}

Then you can create the object with the new keyword.

This allows you to have the polymorphic structure you are looking for. There are other ways that involve copy constructors and references, but are not as straightforward and easy to use.

callyalater
  • 3,102
  • 8
  • 20
  • 27