Example of methods, encapsulation, and constructor in C++

Running

Source Code

main.cpp

#include "square.h"
int main(int argc, char** argv)
{
  Square s1(4);
  cout << "Square with length of " << s1.getLength();
  cout << "\n\nperimeter = " << s1.getPerimeter();
  cout << "\narea = " << s1.getArea() << "\n\n";
  s1.display();
  Square s2(3);
	cout << "\nSquare with length of " << s2.getLength();
	s2.setLength(5);
	cout << "\nJust changed length to " << s2.getLength();
  cout << "\n\nperimeter = " << s2.getPerimeter();
  cout << "\narea = " << s2.getArea() << "\n\n";
  s2.display();
  return 0;
}

square.h

#ifndef SQUARE_H
#define SQUARE_H
#include <iostream>
using namespace std;
class Square
{
	public:
	  Square(const double l = 5);
	  double getPerimeter();
	  double getArea();
	  void setLength(const double l);
	  double getLength();
	  void display();
	private:
	  void validateLength();
	  double length;
};

#endif

square.cpp

#include "square.h"
using namespace std;
Square::Square(const double l)
{
  length = l;
  validateLength();
}

double Square::getPerimeter()
{
  return length * 4;
}

double Square::getArea()
{
  return length * length;
}

void Square::setLength(const double l)
{
  length = l;
  validateLength();
}

double Square::getLength()
{
  return length;
}

void Square::display()
{
  for (int x = 0; x < length; x++)
  {
    for (int y = 0; y < length; y++)
    {
      cout << "*";
    }
    cout << endl;
  }
}

void Square::validateLength()
{
  if (length < 0 || length > 100)
  {
    cout << "Error: length must be from 0 to 100\n";
    exit(1);
  }
}