Difficulty with C++ Triangle Class(OOP)

  area, c++, constructor, oop

I am about to enroll for a course in programming, so I was given this task as a challenge (OOP-related) and for my own knowledge. I can’t even wrap around where to begin. I have searched up similar questions but am still slow and very lost. I apologize for the code because it is embarrassingly lacking, but that is all I have for now. I am at least able to read C++ but w3school alone is not enough for me to put this all together. I would like to see someone’s entire code of this so I can learn from it because this is not to be submitted. Only if you are willing so please if you do not wish to code the whole thing, no worries I just want a shortcut to understand it. (DISCLAIMER: It’s been a week since I’ve started programming on my own bear with me)

A class named Triangle shall represent a triangle. The class shall contain:

  • Three double data fields named side1, side2 and side3 that specify the three sides of the
    triangle. The default values are 1 for all the sides.
  • One string data field named color that specify the color of the triangle. The default value is
    blue for the color.
  • A no-arg constructor that creates a default triangle.
  • A constructor that creates a triangle with the specified sides.
  • The accessor and mutator methods for all the data fields.
  • A method named getArea() that returns the area of this triangle.
  • A method named getPerimeter() that returns the area of this triangle.
  1. Write a test program in C++ that creates two triangle objects. Assign sides 5, 5 and 6 to the first object
    and 1.5, 2.5 and 3.5 to the second object. Display the properties of both objects and find their
    areas and perimeters.
  2. Draw the Class diagram for the program above.
#include<iostream>
#include<string>
using namespace std;

class Triangle {
    private:
        double side1, side2, side3;
        string color;

    public:
        Triangle (double a = 1.0, double b = 1.0, double c = 1.0, string d = "blue") {
            side1 = a;
            side2 = b;
            side3 = c;
            color = d;
        }

        double getSide1() {
            return side1;
        }

        double getSide2() {
            return side2;
        }

        double getSide3() {
            return side3;
        }

        string getColor() {
            return color;
        }
};

int main() {
    Triangle t1(5, 5, 6);
    cout << "Side1 = " << t1.getSide1() << "Side2 = " << t1.getSide2() << "Side3 = " << t1.getSide3() << "Color = " << t1.getColor() << endl;

    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT