0

I'm trying to do exercise from my C++ course and I can't solve this problem. The task is to write suitable classes working with main(given and read only)

int main() {
  Polygon p1 = Polygon::fromLowerLeftToUpperRight(10, 10, 20, 20);
  Polygon p2 = Polygon::fromLowerLeftAndSize(10, 10, 20, 20);
  p1 = Polygon::fromLowerLeftAndSize(10, 10, 10, 10);
  ...
}

Polygon is the class. I dont't know how to use "fromLowerLeftToUpperRight" method instead of constructor.

Cymonello
  • 45
  • 1
  • 9

3 Answers3

3

fromLowerLeftToUpperRight would basically be a static function that returns a Polygon object. Something like this:

class Polygon {

    public:
        static Polygon fromLowerLeftToUpperRight(int, int, int, int);
        static Polygon fromLowerLeftAndSize(int, int, int, int);
        ...    

    private:
        Polygon::Polygon(int, int, int, int);
        ...
}

In these kinds of factory patterns, the constructor is generally kept private so that object creation can only be done using those functions. It is those functions only that can call the constructors.

John Bupit
  • 10,406
  • 8
  • 39
  • 75
2

You can use a factory method instead of using a constructor to create your object.

How to implement the factory method pattern in C++ correctly

coincoin
  • 4,595
  • 3
  • 23
  • 47
1

There are two things you need to know:

First, that any common function may return an object, as long as the object has a callable copy constructor. So, if I have some class MyClass, I could create a ordinary function that returns an instance of it:

MyClass create_instance(int val) {
{
    MyClass inst(val + 42); // Call a constructor

    // Maybe do something else:
    // ...

    return inst; // Return a copy of the object created.
}

So this solves the problem of creating the object without using a constructor directly: in this case, just call create_instance() and takes the return.

Second, that functions called without an instance (i.e. like ClassName::function_name(); instead of object.function_name();) are static member functions, and the only way they differ from ordinary functions is that they can access the private and protected members of the objects of that class, like ordinary member functions.

So all you need to do is create a function that instantiate and returns a Polygon, that also happens to be a static member function of Polygon.

lvella
  • 12,754
  • 11
  • 54
  • 106