Guidance on constructors

Hi, this is my first time posting but I have been reading the forum for some time to usually help me with my own problems. I need help/guidance (I don't want anything handed to me, I want to learn!) on writing code that represents a triangle. I have kind of set up a framework for three constructors and respective functions. There is a 'Private:' as well, can I return the functions declared in it for some of my 'Public' functions? Like wouldn't getVertexOne just return vertex one? Point vertexOne is declared in private, could I just return that?
Sorry my questions are so basic, I'm just a bit lost.

class Triangle: public Shape
{
public:
Triangle();

Triangle(Point pt1, Point pt2, Point pt3, Color color);

Triangle(Point pt1, Color color1,
Point pt2, Color color2,
Point pt3, Color color3);

void setColor(Color color);

void setVertexOne(Point pt);

Point getVertexOne();

void setVertexOneColor(Color color);

Color getVertexOneColor();

void setVertexTwo(Point pt);

Point getVertexTwo();

void setVertexTwoColor(Color color);

Color getVertexTwoColor();

void setVertexThree(Point pt);

Point getVertexThree();

void setVertexThreeColor(Color color);

Color getVertexThreeColor();


private:
Point vertexOne;
Point vertexTwo;
Point vertexThree;
Color vertexOneColor;
Color vertexTwoColor;
Color vertexThreeColor;

//helper functions (given to me)

int evalFunc(int x, int y, int a, int b, int c);
float triArea(int xa, int ya, int xb, int yb, int xref, int yref);
int checkRange(int val);
};
Private items only belong to the class database. To get the value you must set them to public to simply return it.
Thank you. Could I also have advice on how I should use the helper functions given to me?
tibrado wrote:
Private items only belong to the class database. To get the value you must set them to public to simply return it.

No. You can return the value of private fields through a class's interface.
In other words, this is correct:
1
2
3
4
5
6
7
8
9
10
11
class T {
public:
  int getFoo() { return foo; }
private:
  int foo = 0;
};
#include <iostream>

int main (int, char **) {
  std::cout << T{}.getFoo() << "\n";
}


Don't simply mark fields public and leave them to the user unless you know better.

Having accessor and mutator methods (getters and setters) is in general a good idea, and you should do that unless you know they're unlikely to be needed.
Last edited on
There is a 'Private:' as well, can I return the functions declared in it for some of my 'Public' functions?

Yes, class methods can access all private data members and methods of the same class;
getVertexOne just return vertex one? Point vertexOne is declared in private, could I just return that?

Yes, you can as shown in mbozzi's example above

Topic archived. No new replies allowed.