Class creation in C ++

3

I'm developing a project and need to create an inner class. Am I required to create a .cpp and .h?

    
asked by anonymous 16.03.2014 / 15:35

1 answer

1

The place where you define the class will basically influence the access to the definitions by other parts of the code, because for the compiler this will not make much difference.

However, you should consider that when you define functions in the body of the generally class, depending on the settings, the compiler will treat these functions as inline (in fact, you only suggest to the compiler that makes it inline , it will decide if it is viable).

If you implement it only in .cpp you can use it as if it were done in a .h header file, but you can not reuse it in another part of the code if you need to.

If you set everything to main.cpp , for example, it would look 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 Circulo class to a .h , you can reuse the code in other files. And in the case of main.cpp it 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 so, we recommend setting a header for it.

    
16.03.2014 / 16:39