3
I am developing a project and need to create an internal class. I am obliged to create a . cpp and a . h?
3
I am developing a project and need to create an internal class. I am obliged to create a . cpp and a . h?
1
The location where you define the class will basically influence access to the definitions by other snippets of code, because for the compiler this won’t make much difference.
However, you should consider that when you define the functions in the class body itself usually, depending on the settings, the compiler will treat these functions as inline
(in fact, you just suggest to the compiler to do it inline
, he’ll decide if it’s viable).
If you just implement it on .cpp
you can use it as if it were done in a header file .h
, but will not be able to reuse it in another part of the code if you need.
If you set it all on main.cpp
, for example, it would be like this:
#include <iostream>
const float PI = 3.14159265358979323846;
class Circulo
{
public:
Circulo(float raio)
{
m_raio = raio;
}
float getRaio() const
{
return m_raio;
}
void setRaio(float raio)
{
m_raio = raio;
}
float getArea() const
{
return PI * m_raio * m_raio;
}
float getPerimetro() const
{
return PI * m_raio * 2.0f;
}
private:
float m_raio;
};
int main(int argc, char** argv)
{
Circulo circ(5.0f);
std::cout << "Area = " << circ.getArea() << std::endl;
std::cout << "Perimetro = " << circ.getPerimetro() << std::endl;
return 0;
}
Now if you set the class Circulo
in a .h
, you can reuse the code in other files. And in the case of main.cpp
would look like this:
#include "circulo.h"
int main(int argc, char** argv)
{
Circulo circ(5.0f);
std::cout << "Area = " << circ.getArea() << std::endl;
std::cout << "Perimetro = " << circ.getPerimetro() << std::endl;
return 0;
}
The question is whether you will need to reuse the class that gave you this doubt elsewhere. If yes, it is recommended to make a definition in a header for it.
Browser other questions tagged c++ oop classes
You are not signed in. Login or sign up in order to post.
It depends on where you want to apply this class. You can give more details?
– Lucas Lima
I have a program to perform some calculations that depend on other calculations based on a sphere. I thought of creating a class that would store the radius of this one and that would calculate, by means of methods, some information that is interesting, such as perimeter, area and volume.
– user6635
No, you don’t have to, but it makes some things easier.
– Selma