-2

Can I execute some expressions before calling the base class in c++? Particularly, prepare inputs/parameters for the base-constructor. For example:

class Figure {
    Point* vertex;
    Figure(Point vertex[MAX]) {
        this->vertex = vertex;
    }
};

class Triangle: public Figure {
    Triangle(Point p1, Point p2, Point p3) {
      //here it is my question, it is possible?
      Point pts[3] = {p1,p2,p3}; //preparing input for constructor
      Figure(pts); or Figure::Figure(pts); // calling the constructor 
    }
}; 

I am not so sure if this question is specific for C++, maybe it is a general question. Thanks!

Naive Developer
  • 700
  • 1
  • 9
  • 17
  • 1
    In C++ we speak of base and derived classes, not super and sub-classes. And in the code you posted, the base constructor would be called before the derived constructor's code is entered. How to do what you want should be covered in your C++ textbook. –  Sep 22 '18 at 20:58
  • 3
    I suggest you [get a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read. – Some programmer dude Sep 22 '18 at 20:59
  • Your base class doesn't compile by itself. Assigning raw arrays as `this->vertex = vertex;` isn't allowed, and your syntax is invalid too. – Eric Sep 22 '18 at 20:59
  • 2
    You could do something like `Triangle(Point p1, Point p2, Point p3) : Figure(prepare(p1,p2,p3)) { ... }` if you get that to a compilable point as @Eric mentioned. – πάντα ῥεῖ Sep 22 '18 at 21:01
  • 2
    `Figure(Point[] vertex)` is a syntax error. – melpomene Sep 22 '18 at 21:01
  • 1
    @πάνταῥεῖ But `Triangle` doesn't inherit from `Figure`. – melpomene Sep 22 '18 at 21:02
  • @melpomene Oh, I supposed that from all that talk about _super-constructor_ and such. All in all that's a very poor figured question. – πάντα ῥεῖ Sep 22 '18 at 21:03
  • @melpomene: I think that's one of the things wrong with the code, since according to the code structure, it should be derived. – Ben Voigt Sep 22 '18 at 21:11

1 Answers1

0

You could do something with a delegating constructor and list initialization like this if you are willing to change your interfaces slightly and are using c++11 or newer.

#include <vector>

using Point = int;

class Figure
{
    public:
        Figure(const std::vector<Point>& points) : vertices(points) {}

    private:
        std::vector<Point> vertices;
};

class Triangle : public Figure
{
    public:
        Triangle(const Point& p1, const Point& p2, const Point& p3) : Figure({p1, p2, p3}) {}
};

int main(int argc, char** argv)
{
    Point p1 = 1;
    Point p2 = 2;
    Point p3 = 3;

    Triangle t(p1, p2, p3);
}
user1593858
  • 649
  • 7
  • 12