I am learning C++ and I have a question.
I made a class in Netbeans, which made Rectangle.h and Rectangle.cpp. I am trying to add methods that output the Area and Perimeter of the rectangle's l
and w
variables. I don't know how to create methods in a class and how to incorporate them in the Rectangle.h file.
Here's what I'm trying to do:
Rectangle rct;
rct.l = 7;
rct.w = 4;
cout << "Area is " << rct.Area() << endl;
cout << "Perim is " << rct.Perim() << endl;
Can someone explain how to do this? I'm so confused.
Thanks,
Lucas
Methods are also known as the functions of a class. They are primarily used to provide code reusability, which saves computational time and makes the code well structured and clean. Methods also increase code readability since the same set of operations do not need to be written again and again.
Methods are functions that belongs to the class. There are two ways to define functions that belongs to a class: Inside class definition. Outside class definition.
For Java and C#, there are only methods. For C, there are only functions.
There are primarily four storage classes in C, viz. automatic, register, static, and external.
In the .h file you have the class definition, where you write down the member variables en member functions (generally as prototype)
In the .cpp file you declare the methods body. Example:
rectangle.h:
class rectangle
{
public:
// Variables (btw public member variables are not a good
// practice, you should set them as private and access them
// via accessor methods, that is what encapsulation is)
double l;
double w;
// constructor
rectangle();
// Methods
double area();
double perim();
};
rectangle.cpp:
#include "rectangle.h" // You include the class description
// Contructor
rectangle::rectangle()
{
this->l = 0;
this->w = 0;
}
// Methods
double rectangle::area()
{
return this->w * this->l;
}
double rectangle::perim()
{
return 2*this->w + 2*this->l;
}
But like gmannickg said you should read a book about c++ or a real tutorial, that will explain you how the syntax works. And Object Oriented Programming (if you are not familiar with it)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With