samedi 10 novembre 2018

How should I design a class with multiple constructors/methods of initialization

This has probably been asked before, but I couldn't find a satisfying answer. (Apologies for the likely dupe.)

What's the best way to design a class such that objects can be constructed from multiple, different interfaces. A simple example - consider a Circle class..

class Circle
{
private:
    double radius;

public:
    Circle(double rad){
        this->radius = rad;
    };

    // Member functions
    double area() { return 3.14 * std::pow(this->radius, 2); };
};

This works, but in order to construct the circle I have to provide its radius. How can I allow the user to construct a new circle object from its radius or its area or its circumference?

Aucun commentaire:

Enregistrer un commentaire