The best way to create a c++ class



  • hi everybody,
    to create a c++ class i can do the following

    1. first way:

    Personnage.cpp
    @
    #include <iostream>
    using namespace std;
    class Personnage
    {
    public:
    Personnage();
    ~Personnage();
    int getVie();
    protected:
    private:
    int vie;
    };
    @
    in the file "main.cpp"
    i can write
    @
    #include <iostream>
    #include "Personnage.cpp"

    using namespace std;
    int main()
    {

    cout << "Hello world!" << endl;
    Personnage david;
    return 0;
    

    }
    @

    1. But it is also possible
      to create a header file that i will include in the main like this :

    Personnage.h
    @
    #ifndef PERSONNAGE_H
    #define PERSONNAGE_H

    class Personnage
    {
    public:
    Personnage();
    ~Personnage();
    int getVie();
    protected:
    private:
    int vie;
    };

    #endif
    @
    Personnage.cpp
    @
    #include<iostream>
    #include<string>
    #include "Personnage.h"

    using namespace std ;

    Personnage::Personnage():vie(2)
    {
    //

    }

    Personnage::~Personnage()
    {

    }
    int Personnage::getVie(){
    return vie ;
    }
    @

    and finally in the main.cpp
    @
    #include <iostream>
    #include "Personnage.h"

    using namespace std;
    /** \brief
    *
    * \param
    * \param
    * \return
    *
    */
    int main()
    {

    cout << "Hello world!" << endl;
    Personnage david;
    //cout<<david.getVie()<<endl;
    return 0;
    

    }
    @
    so i want to know what is the best way to create a c++ class is it good to include directly a sourcefile.cpp which contains the definition of the class ? thanks

    Edit: please use @ tags around code sections; Andre



  • [quote author="landing kiss" date="1360936159"]
    so i want to know what is the best way to create a c++ class is it good to include directly a sourcefile.cpp which contains the definition of the class ? thanks
    [/quote]

    It is better to split source code into several files and to rely on header files. It is also recommended to use #include macro guards to make sure that the file was been include only once (aka to avoid double or multiple inclusion).



  • Hi,
    I have an example explaining the right way to create a C++ program.

    The source code can be downloaded here :

    "developpez.com":http://cpp.developpez.com/telecharger/detail/id/2955/Liste-de-Personnes

    :)



  • thanks ! effectively it is better to avoid several inclusion


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.