Mustafa
Mustafa

Reputation: 177

c++ structs as private data member

I have a project using the CImg library. What I have to do is declare classes that inherit from an abstract base class called shape. These classes are classes for the different shapes(circle, rectangle .. etc). What I want to do is use a struct class called point for the different points that I need for every class. So for example, for a triangle shape, I have to use three points to draw a triangle with each point having an x coordinate and a y-coordinate. So here's what I got so far.

class Shape
{
public:
    virtual void draw_shape() = 0;
    virtual double area() = 0;
};

struct Point
{
    const int x; //const is necessary because CImg drawing functions require them.
    const int y;
};

class Triangle : public Shape
{
private:
    struct Point first;
    struct Point second;
    struct Point third;
public:
    Triangle();
    Triangle(const int, const int, const int, const int, const int, const int);
    virtual void draw_shape();
    virtual double area();
};

1) How do I initialize the x-coordinate and y-coordinate of each struct ?

Triangle::Triangle() : first.x(0), first.y(0), second.x(0), second.y(0), third.x(0), third.y(0)

does not work

2) Is my overloaded constructor correct or should I use this constructor:

Triangle(Point, Point, Point);

3) How do i use the points after this whenever I want to draw something ?! 4) Is the struct before instantiating the Points necessary in c++?

Upvotes: 0

Views: 568

Answers (2)

gexicide
gexicide

Reputation: 40048

Considering 1)

You can simply use this:

Triangle::Triangle() : first{0,0}, second{0,0}, third{0,0} {}

Considering 2) I think that the constructor

Triangle(Point, Point, Point); 

is better. When you already have points, why not using them?

Considering 3) dependons on how things get drawn

Considering 4) No, it is not necessary.

Upvotes: 1

Rook
Rook

Reputation: 6145

You can invoke the constructors of your points, like this:

Triangle() : first{0, 0}, second{0, 0}, third{0, 0} {}

You can add an explicit constructor yourself, if you wanted to do something a little more complex:

struct Point
{
    int x;
    int y;

    Point(int a, int b) : x(a), y(b) { /* ... */ }
};

Upvotes: 1

Related Questions