Mat
Mat

Reputation: 4501

c++ how to return object of current classes type (inheritance)

I'd like to do something like this:

class A{
public:
    A(int i);

    static A* createWithSpecialCalculation(int a, int b, int c){
      // ...complex calculation here...
      return new A(result_of_calculation);
    }
};

class B:A{
public:
    float m_additionalMember;
};

now I want to be able to call

B* myB = B::createWithSpecialCalculation(1,2,3);

Is this possible somehow? if so, how?

Upvotes: 0

Views: 191

Answers (2)

Loki Astari
Loki Astari

Reputation: 264331

How about:
Just change the definition of createWithSpecialCalculation in A slightly.

template<typename T>
static T* createWithSpecialCalculation(int a, int b, int c){
  // ...complex calculation here...
  return new T(result_of_calculation);
}

Then you can go:

B* myB = A::createWithSpecialCalculation<B>(1,2,3);

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

Inheritance may not be appropriate here.

Instead, consider a free template function:

template <typename T>
T* createOne(int a, int b, int c) {
   int x = complexCalculation(a,b,c);
   return new T(x);
}

That is, if the argument(s) to the constructor will be the same no matter the type A or B; from your desire to avoid any code duplication, it sounds like that's already helpfully the case.

A* myA = createOne<A>(1,2,3);
B* myB = createOne<B>(1,2,3);

Consider shared_ptr<> rather than these raw pointers, though.

Upvotes: 0

Related Questions