Broak
Broak

Reputation: 4187

Inheritance, defining a function for creating an object of a specified type?

Title does not help im sure.

Anyway, at the moment i'm working with the following

http://puu.sh/7wJed.png

Everything's fine and inherited correctly, however, in order to create an object of say 'aircraftCarrier' i'd need to pass the 12 values + the two inherited values every-time i want to use a function such as

generateAirCraftCarrier(1,2,3,4,5,6,7,8,9,10,11,12);

I could simply pass in a navalVessel instance into the function instead, such that

generateAirCraftCarrier(myNavalVessel, inherit var 1, inherit var 2);

BUT this would not be entirely a solution because what happens when the aircraft carrier has a different 'Speed' for example?

can i have option parameters, which if null use the myNavalVessel object? Looking for some guidance here, sorry about the gibberish.

Upvotes: 0

Views: 47

Answers (2)

Chris Drew
Chris Drew

Reputation: 15334

Why do you need one function to define all 12 values on an AircraftCarrier? Why not build it up with a number of setters on AircraftCarrier and NavalVessel? e.g:

class NavalVessel {
  float speed_;

public:
  void setSpeed(float speed) { speed_ = speed; }
};

class AircraftCarrier : public NavalVessel {
  int noHeliPads_;
  int noRunways_;

public:
  void setNoHeliPads(int noHeliPads) { noHeliPads_ = noHeliPads; }
  void setNoRunways(int noRunways) { noRunways_ = noRunways; } 
};


int main() {
    AircraftCarrier aircraftCarrier;
    aircraftCarrier.setSpeed(25.3);
    aircraftCarrier.setNoHeliPads(3);
    aircraftCarrier.setNoRunways(2);
}

Upvotes: 1

Oleg Andriyanov
Oleg Andriyanov

Reputation: 5279

Could named parameters idiom be useful for you?

class AircraftCarrierParameters;

class AircraftCarrier
{
private:
    AircraftCarrierParameters _params;
public:
    AircraftCarrier(const AircraftCarrierParameters& params)
        : _params(params) {}
    AircraftCarrierParameters params() const { return _params;}
};

class AircraftCarrierParameters
{
private:
    double _speed;
    int _someOtherStuff;

public:
    AircraftCarrierParameters()
        : _speed(0)             //default parameters
        , _someOtherStuff(0)
    {

    }
    double speed() const { return _speed; }
    double someOtherStuff() const { return _someOtherStuff; }

    AircraftCarrierParameters& setSpeed(double speed) { _speed = speed; return *this; }
    AircraftCarrierParameters& setSomeOtherStuff(double stuff) { _someOtherStuff = stuff; return *this; }
};

AirCraftCarrier generateAirCraftCarrier(const AircraftCarrierParameters& params)
{
    //...
}

void main()
{
    AircraftCarrier c1(AircraftCarrierParameters());
    AircraftCarrier c2(c1.params().setSpeed(30));
}

Upvotes: 0

Related Questions