Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

separating class into header and cpp file

//header file(.h)
//Implement function headers
#pragma once

class Rectangle
{
private:
	float length;
	float width;
public:
	//constructor
	Rectangle();

	//setters
	void setLength(float l);
	void setWidth(float w);

	//getters
	float getLength();
	float getWidth();

	//Calculating area
	float area(float length, float width);

	//print
	void print();
};

//(.cpp) file
//Function definations
#include <iostream>
#include "Rectangle.h"

using namespace std;

//constructor
Rectangle::Rectangle() {
	length = width = 0;
}

//setters
void Rectangle::setLength(float l) {
	length = l;
}
void Rectangle::setWidth(float w) {
	width = w;
}

//getters
float Rectangle::getLength() {
	return length;
}
float Rectangle::getWidth() {
	return width;
}

//Calculating area
float Rectangle::area(float length, float width) {
	float a = (float)length * width;
	return a;
}
 //print
void Rectangle::print() {
	cout << "Length= " << getLength() << endl;
	cout << "Width= " << getWidth() << endl;
	cout << "Area= " << area(length, width) << endl;
}

//main .cpp file
#include <iostream>
#include "Rectangle.h"

using namespace std;

int main() {
	float length, width;
	Rectangle rectangle;
	cout << "Enter length of the rectangle: ";
	cin >> length;
	cout << "Enter width of the rectangle: ";
	cin >> width;
	rectangle.setLength(length);
	rectangle.setWidth(width);
	rectangle.print();
}
 
PREVIOUS NEXT
Tagged: #separating #class #header #cpp #file
ADD COMMENT
Topic
Name
7+9 =