-1

Write a C++ class code to calculate the area of a rectangle as illustrated in the following figure.
Your code must be in a Project contains 3 separate files.

  • Implementation file (.cpp)
  • Header file (.h)
  • Main file (.cpp)

Here is the image for the question:

image

Code:

main.cpp:

   #include "area.h"
   #include <iostream>
   using namespace std;
   int main(int argc, char *argv[])
   {

       Rectangle obj;
       obj.setLength(8);
       obj.setWidth(3);
       cout<<"Area of Rectangle : "<<obj.getArea();
       cout<<endl;

       return 0;
   }

area.h:

   #include <iostream>
   using namespace std;
   #ifndef area_h
   #define area_h

  class Rectangle
  {
       public:
       double length, width,Area;
       Rectangle();     
       double setLength(int a );
       double setWidth(int b);
       double getArea();
  };
  #endif

area.cpp:

#include "area.h"

Rectangle::Rectangle()

double Rectangle::setLength(int a)
{length = a}
double Rectangle::setWidth(int b)
{width = b}

 double Rectangle::getArea(){return Area= a * b;}

When i run the code, it shows this error:

ide screenshot

SuperStormer
  • 4,997
  • 5
  • 25
  • 35

1 Answers1

0

I don't know how your IDE works, but you need to either link in the object file for area.cpp when you're compiling main.cpp, or you need to compile both at the same time, eg. g++ -Wall -Wextra main.cpp area.cpp.

After you fix the linking issues, you need to change getArea to:

double Rectangle::getArea(){
    Area = length * width;
    return Area;
}

as a and b are both undefined.

Next, you have a bunch of syntax errors that should be corrected, such as missing semicolons.

Finally, both setLength and setWidth should be void, not double as they don't return anything.

Rewritten area.cpp:

#include "area.h"

void Rectangle::setLength(int a){
    length = a;
}
void Rectangle::setWidth(int b){
    width = b;
}

double Rectangle::getArea(){
    Area = length * width;
    return Area;
}

Other helpful links, though not directly related:

"std::endl" vs "\n"

Why is "using namespace std;" considered bad practice?

SuperStormer
  • 4,997
  • 5
  • 25
  • 35