Skip to main content

Triangle perimeter with constructors

Short answer

A Triangle class defines a default constructor that sets all sides to 1 and a parameterized constructor accepting three side lengths. Perimeter is the sum of the sides. Example: default object perimeter = 3 units; object with sides 3,4,5 perimeter = 12 units.

Write a program to calculate the Perimeter of Triangle using Default and Parameterized constructors.

The class has a default constructor (sets all sides to a default of 1) and a parameterized constructor (sets the three sides). The perimeter is the sum of the three sides.

#include <iostream>
using namespace std;

class Triangle
{
    float a, b, c;
public:
    Triangle()                          // default constructor
    {
        a = b = c = 1;
    }
    Triangle(float x, float y, float z) // parameterized constructor
    {
        a = x;
        b = y;
        c = z;
    }
    float perimeter()
    {
        return a + b + c;
    }
};

int main()
{
    Triangle t1;                        // default
    Triangle t2(3, 4, 5);               // parameterized

    cout << "Perimeter of t1 = " << t1.perimeter() << endl;
    cout << "Perimeter of t2 = " << t2.perimeter() << endl;
    return 0;
}

Output

Perimeter of t1 = 3
Perimeter of t2 = 12

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →