Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class methods

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

like image 854
Lucas Avatar asked Mar 26 '12 22:03

Lucas


People also ask

What are methods in C?

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.

What is class methods C++?

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.

Are there methods in C?

For Java and C#, there are only methods. For C, there are only functions.

How many types of class are there in C?

There are primarily four storage classes in C, viz. automatic, register, static, and external.


1 Answers

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)

like image 164
grifos Avatar answered Oct 06 '22 00:10

grifos