A.Saeed
A.Saeed

Reputation: 3

Returning a Derived Class Object from a function of the Base Type

Say i have three classes one called character, one ork and one human. Human and ork are both derived from character. Is there anyway to create a function of type character and inside that function be able to return objects created from either the ork or human classes. Or maybe there is another way of returning either ork or human objects from the same function.

Edit: Nevermind folks it turns out when i tried this earlier i accidentally derived ork and human from a different class. It is in fact possible to return a derived class from a function of base type. Just to be clear this is what i was doing.

character game::getPlayer(char symbol) { switch (symbol) { case 'E': return elfPlayer; break; case 'G': return guardPlayer; break; case 'K': return knightPlayer; break; case 'R': return roguePlayer; break; case 'W': return wizardPlayer; break; } }

Upvotes: 0

Views: 5210

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

Let's first say you want to return a value of derived class, that's simple:

struct Derived;

struct Base { auto foo() -> Derived; };

struct Derived: Base {};

auto Base::foo() -> Derived { return {}; }

But with this approach, if foo is to return either a Derived1 or a Derived2, then its return type must be the common base class of those two (or higher), and the result will then be sliced to that base class.

So for the multiple possible dynamic return types you need to return a pointer or a reference, e.g.,

struct Base
{
    auto foo() -> unique_ptr<Base>;
    virtual ~Base() {}
};

struct Derived1: Base {};
struct Derived2: Base {};

auto Base::foo()
    -> unique_ptr<Base>
{ return {garble_voff? new Derived1 : new Derived2}; }

When directly using a simple unique_ptr you need to have a virtual destructor in class Base, to support a simple delete expression.

Disclaimer: none of the code touched by a compiler.

Upvotes: 1

Achiko Mezvrishvili
Achiko Mezvrishvili

Reputation: 226

If i pictured correctly , u need one pure virtual function inside the base class Character and entire function would be used in derived classes in Human and Orc.

class  Character
{
   public: 
       Character();
    virtual ~Character();

    virtual  HRESULT  Characterfunc() = 0; 

private: 

}

and then in derived classes:

 class  Ork :  public Character
{
   public: 
         Ork();

  HRESULT Characterfunc();      

private:

}

And the last one:

 class  Human :  public Character
{
   public: 
         Human();

  HRESULT Characterfunc();      

private:

}

Upvotes: 0

Related Questions