CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Oct 2016
    Posts
    16

    how to compress the code while getting the same results?

    I am a newbie and this is a small program I wrote with what I have learned so far since I started coding in C++ about a week ago.

    ¿how to compress the code to minimum, while getting the same results?

    ejercicio2.cpp

    Code:
    #include<iostream>
    #include"opciones.h"
    #include"multi.h"
    #include"mensaje.h"
    #include"div.h"
    #include"cuadricula.h"
    
    using namespace std;
    
    int main()
    
    {
        int val1;
        int val2;
        int repe;
    
        mensaje miMensaje1;
        miMensaje1.mostrarMensaje();
    
        while( repe != 2 )
    
        {
            cout << "Introduce el primer valor : ";
            cin  >> val1;
    
            cout << "\n\nIntroduce el segundo valor : ";
            cin  >> val2;
    
            cout << "\n\n";
    
            opciones opc1( val1, val2 );
            multi multiple1( val1, val2 );
            div divicion1( val1, val2 );
            cuadricula miCuadricula;
    
            cout << "El resultado de la suma es : " << opc1.obtenerResultado() << "!" << endl;
    
            cout << "\n\nEL resultado de la multiplicacion es : " << multiple1.obtenerResultado() << "!" << endl;
    
            cout << "\n\nEl resultado de la division es : " << divicion1.obtenerResultado() << "!" << endl;
    
            cout << "\n\n\n\n";
    
            miCuadricula.mostrarCuadricula();
    
            cout << "\n\nDeseas seguir usando el programa? : ( 1 )SI  ( 2 )NO  :  ";
    
            cin  >> repe;
    
        }
    
        miMensaje1.mostrarDespedida();
    }
    opciones.h

    Code:
    #define OPCIONES_H_INCLUDED
    #endif // OPCIONES_H_INCLUDED
    
    class opciones
    
    {
        public:
    
            explicit opciones( int, int );
    
            void establecerDatos( int, int );
    
            int obtenerResultado() const;
    
        private:
    
            int opcion1;
            int opcion2;
            int resultado;
    
    };
    opciones.cpp

    Code:
    #include<iostream>
    #include"opciones.h"
    
    using namespace std;
    
    opciones::opciones( int op1, int op2 )
    
        :opcion1( op1 ), opcion2( op2 ), resultado(opcion1 + opcion2)
    
    {
    
    }
    
    void opciones::establecerDatos( int op1, int op2 )
    
    {
        opcion1 = op1;
        opcion2 = op2;
        resultado = opcion1 + opcion2;
    }
    
    int opciones::obtenerResultado() const
    
    {
        return resultado;
    }
    multi.h

    Code:
    #define MULTI_H_INCLUDED
    #endif // MULTI_H_INCLUDED
    
    class multi
    
    {
        public:
    
            explicit multi( int, int );
    
            void establecerDatos( int, int );
    
            int obtenerResultado() const;
    
        private:
    
            int opcion1;
            int opcion2;
            int resultado;
    
    };
    multi.cpp

    Code:
    #include<iostream>
    #include"multi.h"
    
    using namespace std;
    
    multi::multi( int op1, int op2 )
    
        :opcion1( op1 ), opcion2( op2 ), resultado(opcion1 * opcion2)
    
    {
    
    }
    
    void multi::establecerDatos( int op1, int op2 )
    
    {
        opcion1 = op1;
        opcion2 = op2;
        resultado = opcion1 * opcion2;
    }
    
    int multi::obtenerResultado() const
    
    {
        return resultado;
    }
    mensaje.h

    Code:
    #ifndef MENSAJE_H_INCLUDED
    #define MENSAJE_H_INCLUDED
    #endif // MENSAJE_H_INCLUDED
    
    #include<string>
    
    class mensaje
    
    {
        public:
    
            explicit mensaje();
    
            void mostrarMensaje() const;
    
            void mostrarDespedida() const;
    
        private:
    
            std::string texto;
    
    };
    mensaje.cpp

    Code:
    #include<iostream>
    #include"mensaje.h"
    
    using namespace std;
    
    mensaje::mensaje()
    
    {
    }
    
    void mensaje::mostrarMensaje() const
    
    {
        cout << "Bienvenido a calculos v1.0 ! \n\n";
    }
    
    void mensaje::mostrarDespedida() const
    
    {
        cout << "\n\nGracias por usar calculos v1.0 ! \n\n";
    }
    div.h

    Code:
    #ifndef DIV_H_INCLUDED
    #define DIV_H_INCLUDED
    #endif // DIV_H_INCLUDED
    
    class div
    
    {
        public:
    
            explicit div( double, double );
    
            void establecerDatos( double, double );
    
            double obtenerResultado() const;
    
        private:
    
            double opcion1;
            double opcion2;
            double resultado;
    
    };
    div.cpp

    Code:
    #include<iostream>
    #include"div.h"
    
    using namespace std;
    
    div::div( double op1, double op2 )
    
        :opcion1( op1 ), opcion2( op2 ), resultado(opcion1 / opcion2)
    
    {
    
    }
    
    void div::establecerDatos( double op1, double op2 )
    
    {
        opcion1 = op1;
        opcion2 = op2;
        resultado = opcion1 / opcion2;
    }
    
    double div::obtenerResultado() const
    
    {
        return resultado;
    }
    cuadricula.h

    Code:
    #ifndef CUADRICULA_H_INCLUDED
    #define CUADRICULA_H_INCLUDED
    #endif // CUADRICULA_H_INCLUDED
    
    
    class cuadricula
    
    {
        public:
    
            explicit cuadricula();
    
            void mostrarCuadricula() const;
    
        private:
    
            char simbolo = '*';
    };
    cuadricula.cpp

    Code:
    #include<iostream>
    #include"cuadricula.h"
    
    using namespace std;
    
    cuadricula::cuadricula()
    
    {
    }
    
    void cuadricula::mostrarCuadricula() const
    
    {
        int x;
    
        cout << "*********************************************************\n";
    
        for( x = 0; x < 8; x++ )
    
        {
            cout << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "      "
                 << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "\n";
            cout << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "      "
                 << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "\n";
            cout << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "      "
                 << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "      " << simbolo << "\n";
            cout << "*********************************************************\n";
    
        }
    }

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: how to compress the code while getting the same results?

    Quote Originally Posted by sauerplayer;2218449¿how to compress the code to minimum, while getting the same results?
    ...
    [code
    void multi::establecerDatos( int op1, int op2 )

    {
    opcion1 = op1;
    opcion2 = op2;
    resultado = opcion1 * opcion2;
    }

    [/code]
    You could change it like:
    1.
    Code:
    void multi::establecerDatos( int op1, int op2 )
    {
        resultado = op1 * op2;
    }
    2. remove the empty lines.
    Victor Nijegorodov

  3. #3
    Join Date
    Oct 2016
    Posts
    16

    Re: how to compress the code while getting the same results?

    Nice thanks, and btw another question I have is: ¿is it necesary to use the code below?

    Code:
    opciones::opciones( int op1, int op2 )
    
        :opcion1( op1 ), opcion2( op2 ), resultado(op1 + op2)
    
    {
    
    }
    and

    Code:
    void opciones::establecerDatos( int op1, int op2 )
    
    {
        resultado = op1 + op2;
    }
    or just:

    Code:
    void opciones::establecerDatos( int op1, int op2 )
    
    {
        resultado = op1 + op2;
    }
    will do?

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: how to compress the code while getting the same results?

    Quote Originally Posted by sauerplayer View Post
    Nice thanks, and btw another question I have is: ¿is it necesary to use the code below?

    Code:
    opciones::opciones( int op1, int op2 )
    
        :opcion1( op1 ), opcion2( op2 ), resultado(op1 + op2)
    
    {
    
    }
    Well, it is a ctor with two arguments, abd it also initialises the class members opcion1, opcion2, resultado.
    It may be useful if you furser will use somehow these class members.

    Quote Originally Posted by sauerplayer View Post
    ...
    or just:

    Code:
    void opciones::establecerDatos( int op1, int op2 )
    
    {
        resultado = op1 + op2;
    }
    will do?
    It is a class method that sets the member resultado as a sum of two transfered arguments.
    Victor Nijegorodov

  5. #5
    Join Date
    Feb 2017
    Posts
    677

    Re: how to compress the code while getting the same results?

    You don't need to divide the code into .h and .cpp files. It's just an old convention (not required by the C++ language) and it's getting increasingly obsolete. The idea was that programmers could "help" compilers by splitting the code into manageable chunks but today's compilers are so smart that programmers are just getting in the way when trying to help. So you can equally well put the implementation code you now have in the .cpp files in the definitions on the .h files and leave it to the compiler to decide what divisions of the code will result in an optimal program.

    I have tested this approach quite extensively with thousands of .h files and just one .cpp file holding the program entry point (that is main()) and it works perfectly fine and compiles very quickly. I'm using VS 2017 and it keeps tabs down to individual functions of what needs to be recompiled after a change you made (and even informs you what percentage of the whole program got changed).

    In this way, by cutting the number of files holding your program in half, you get a much simpler program to manage.
    Last edited by wolle; October 27th, 2017 at 05:16 PM.

  6. #6
    Join Date
    Oct 2016
    Posts
    16

    Re: how to compress the code while getting the same results?

    Quote Originally Posted by wolle View Post
    You don't need to divide the code into .h and .cpp files. It's just an old convention that's getting increasingly obsolete. The idea was that programmers could "help" compilers by splitting the code into manageable chunks but today compilers are so smart that programmers are just getting in the way when trying to help. So you can equally well put the implementation code you now have in the .cpp files in the definitions on the .h files.

    I have tested this approach quite extensively with thousands of .h files and just one .cpp file holding the program entry point (that is main()) and it works perfectly fine and compiles very quickly.

    In this way, by cutting the number of files holding your program in half, you get a much simpler program to manage.
    Omg that was an excellent well explained and detailed answer , the reason I wrote my program like that was because I use how to program in C++ v9 by deitel & deitel book and examples, and it explains how to make programs using both .cpp and .h files for each class you create, now that I know that this method is just and old convention that's getting increasingly obsolete I will use it no more, thanks

  7. #7
    Join Date
    Oct 2016
    Posts
    16

    How good is this code, speaking of good coding and optimization for a newbie?

    Menu.cpp

    Code:
    #include<iostream>
    #include"suma.h"
    #include"resta.h"
    #include"multi.h"
    #include"mensaje.h"
    #include"div.h"
    #include"cuadricula.h"
    
    using namespace std;
    
    int main()
    
    {
        int val1;
        int val2;
        int repe;
        int seleccion;
    
        mensaje miMensaje1;
        miMensaje1.mostrarMensaje();
    
        while( repe != 2 )
    
        {
            cout << "Escoge la opcion deseada \n(1)suma, (2)resta, (3)multiplicacion, (4)divicion, (5)cuadricula : ";
    
            cin  >> seleccion;
    
            switch( seleccion )
    
            {
    
                case 1:
    
                {
                    cout << "Introduce el primer valor : ";
                    cin  >> val1;
    
                    cout << "\n\nIntroduce el segundo valor : ";
                    cin  >> val2;
    
                    cout << "\n\n";
                    suma suma1( val1, val2 );
                    cout << "El resultado de la suma es : " << suma1.obtenerResultado() << "!" << endl;
                }
    
                break;
    
                case 2:
    
                {
                    cout << "Introduce el primer valor : ";
                    cin  >> val1;
    
                    cout << "\n\nIntroduce el segundo valor : ";
                    cin  >> val2;
    
                    cout << "\n\n";
                    resta resta1( val1, val2 );
                    cout << "\n\nEL resultado de la resta es : " << resta1.obtenerResultado() << "!" << endl;
                }
    
                break;
    
                case 3:
    
                {
                    cout << "Introduce el primer valor : ";
                    cin  >> val1;
    
                    cout << "\n\nIntroduce el segundo valor : ";
                    cin  >> val2;
    
                    cout << "\n\n";
                    multi multiple1( val1, val2 );
                    cout << "\n\nEL resultado de la multiplicacion es : " << multiple1.obtenerResultado() << "!" << endl;
                }
    
                break;
    
                case 4:
    
                {
                    cout << "Introduce el primer valor : ";
                    cin  >> val1;
    
                    cout << "\n\nIntroduce el segundo valor : ";
                    cin  >> val2;
    
                    cout << "\n\n";
                    div divicion1( val1, val2 );
                    cout << "\n\nEl resultado de la division es : " << divicion1.obtenerResultado() << "!" << endl;
                }
    
                break;
    
                case 5:
    
                {
                    cuadricula miCuadricula;
                    miCuadricula.mostrarCuadricula();
                }
    
                break;
    
            }
    
                cout << "\n\nDeseas seguir usando el programa? : ( 1 )SI  ( 2 )NO  :  ";
                cin  >> repe;
    
        }
    
        miMensaje1.mostrarDespedida();
    }
    suma.h

    Code:
    #ifndef SUMA_H_INCLUDED
    #define SUMA_H_INCLUDED
    #endif // SUMA_H_INCLUDED
    
    #include<iostream>
    
    using namespace std;
    
    class suma
    
    {
        public:
    
            explicit suma( int op1, int op2 )
    
            :opcion1( op1 ), opcion2( op2 ), resultado(op1 + op2)
    
            {
            }
    
            void establecerDatos( int op1, int op2 )
    
            {
                resultado = op1 + op2;
            }
    
            int obtenerResultado() const
    
            {
                return resultado;
            }
    
    
        private:
    
            int opcion1;
            int opcion2;
            int resultado;
    };
    multi.h

    Code:
    #ifndef MULTI_H_INCLUDED
    #define MULTI_H_INCLUDED
    #endif // MULTI_H_INCLUDED
    
    #include<iostream>
    
    using namespace std;
    
    class multi
    
    {
        public:
    
            explicit multi( int op1, int op2 )
    
            :opcion1( op1 ), opcion2( op2 ), resultado(op1 * op2)
    
            {
            }
    
            void establecerDatos( int op1, int op2 )
    
            {
                resultado = op1 * op2;
            }
    
            int obtenerResultado() const
    
            {
                return resultado;
            }
    
        private:
    
            int opcion1;
            int opcion2;
            int resultado;
    
    };
    mensaje.h

    Code:
    #ifndef MENSAJE_H_INCLUDED
    #define MENSAJE_H_INCLUDED
    #endif // MENSAJE_H_INCLUDED
    
    #include<iostream>
    
    using namespace std;
    
    class mensaje
    
    {
        public:
    
            explicit mensaje()
    
            {
            }
    
            void mostrarMensaje() const
    
            {
                cout << "Bienvenido a calculos v1.0 ! \n\n";
            }
    
            void mostrarDespedida() const
    
            {
                cout << "\n\nGracias por usar calculos v1.0 ! \n\n";
            }
    
    
        private:
    
            string texto;
    };
    div.h

    Code:
    #ifndef DIV_H_INCLUDED
    #define DIV_H_INCLUDED
    #endif // DIV_H_INCLUDED
    
    #include<iostream>
    
    using namespace std;
    
    class div
    
    {
        public:
    
            explicit div( double op1, double op2 )
    
            :opcion1( op1 ), opcion2( op2 ), resultado(op1 / op2)
    
            {
            }
    
            void establecerDatos( double op1, double op2 )
    
            {
                resultado = op1 / op2;
            }
    
            double obtenerResultado() const
    
            {
                return resultado;
            }
    
    
        private:
    
            double opcion1;
            double opcion2;
            double resultado;
    
    };
    cuadricula.h

    Code:
    #ifndef CUADRICULA_H_INCLUDED
    #define CUADRICULA_H_INCLUDED
    #endif // CUADRICULA_H_INCLUDED
    
    #include<iostream>
    
    using namespace std;
    
    class cuadricula
    
    {
        public:
    
            explicit cuadricula()
    
            {
            }
    
            void mostrarCuadricula() const
    
            {
    
                int x;
                int y;
                int z;
    
                cout << "*********************************************************\n";
    
                for( x = 0; x < 8; x++ )
    
                {
                    for( z = 0; z < 3; z++ )
    
                    {
    
                        for( y = 0; y < 9; y++ )
    
                        {
                            cout << simbolo << "      ";
                        }
    
                        cout << "\n";
    
                    }
    
                    cout << "*********************************************************\n";
                }
            }
    
        private:
    
            char simbolo = '*';
    };
    resta.h

    Code:
    #ifndef RESTA_H_INCLUDED
    #define RESTA_H_INCLUDED
    #endif // RESTA_H_INCLUDED
    
    #include<iostream>
    
    using namespace std;
    
    class resta
    
    {
        public:
    
            explicit resta( int op1, int op2 )
    
            :opcion1( op1 ), opcion2( op2 ), resultado(op1 - op2)
    
            {
            }
    
            void establecerDatos( int op1, int op2 )
    
            {
                resultado = op1 - op2;
            }
    
            int obtenerResultado() const
    
            {
                return resultado;
            }
    
    
        private:
    
            int opcion1;
            int opcion2;
            int resultado;
    };

  8. #8
    Join Date
    Oct 2008
    Posts
    1,456

    Re: how to compress the code while getting the same results?

    Quote Originally Posted by sauerplayer View Post
    make programs using both .cpp and .h files for each class you create, now that I know that this method is just and old convention that's getting increasingly obsolete I will use it no more, thanks
    In your case, it surely makes little sense to split everything in that way ( indeed, placing one-liners into cpp files would not even pass code review in some coding guidelines ).

    But claiming that separate compilation is an "obsolete convention" is a questionable opinion. Seperate compilation is a tool, and as every tool may or may not fit your needs, with its pros and cons. It depends on the specific project details, including the whole ecosystem of languages/tools involved in the production/maintenance process ( compilers/linkers/build systems/doc generators/versioning systems/... ).

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: How good is this code, speaking of good coding and optimization for a newbie?

    [threads merged as one follows from the other]

    A few comments.

    Explicit is only really necessary when the constructor takes a single argument and you don't the compiler to automatically invoke it for a cast conversion.

    There is no need to save constructor parameters if they are not going to be used in other class functions.

    For reasons you'll come on to later re performance, pre inc(dec) is preferred to post inc(dec) unless there is a reason why post is required.

    In main(), you are not initialising repe before it is used.
    Last edited by 2kaud; October 28th, 2017 at 05:27 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  10. #10
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: how to compress the code while getting the same results?

    I have tested this approach quite extensively with thousands of .h files and just one .cpp file
    Note that the file name used with #include can be any file located in the search folders. It needn't have a .h extension - it can have any extension. Also note that these files can contain any valid c/c++ code.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  11. #11
    Join Date
    Feb 2017
    Posts
    677

    Re: how to compress the code while getting the same results?

    Quote Originally Posted by superbonzo View Post
    But claiming that separate compilation is an "obsolete convention" is a questionable opinion. Seperate compilation is a tool, and as every tool may or may not fit your needs, with its pros and cons. It depends on the specific project details, including the whole ecosystem of languages/tools involved in the production/maintenance process ( compilers/linkers/build systems/doc generators/versioning systems/... ).
    Okay maybe I overdid it a little.

    Still I think it's fair to say that the routine splitting into .h and .cpp is a convention that is becoming increasingly obsolete. Note for example the increasing number of C++ libraries (like say in Boost) that are published as .h only and that this is considered an advantage.

    Unfortunately education is lagging and the splitting into .h and .cpp is often presented as a hallmark of correct C++ code (that should be performed routinely because that's how proper C++ programs look like and that it will "help" the compiler to do its work). I think it should rather be the other way around, that .h files are preferred and that translation units and .cpp files are considered a more advanced feature you are taught why and when best to use. It should not be withheld from students that splitting is a practice not required by C++ and that having just one translation unit is perfectly fine.

    My current strategy is to use .h files only, knowing that it's always possible to later "tie down" the .h files you want to form a translation unit by #include them in a .cpp file you introduce for that purpose. In this way the program design becomes independent of issues concerning the program management.

    I must admit I was a little uneasy to try this at first but it has worked out just fine (with a medium-sized molecular simulation program (about 500 .h source files so far and one .cpp file holding wWinMain) developed in VS 2017 Community using WTL 10 and Direct3D 12 with me as sole programmer). I'm into OO so I have lots of classes and I find it very convenient to keep everything concerning one class on one file (maybe due to my Java background but anyway). I feel I got rid of a complication and I'm sure the compiler is happy not having me meddling in.
    Last edited by wolle; October 29th, 2017 at 04:37 AM.

  12. #12
    Join Date
    Oct 2008
    Posts
    1,456

    Re: how to compress the code while getting the same results?

    >>Still I think it's fair to say that the routine splitting into .h and .cpp is a convention that is becoming increasingly obsolete.[...]I think it should rather be taught the other way around, that .h files are used unless there'a a good reason not to. Then compilation units and .cpp files would be seen as a more advanced feature of C++ you were taught how and when best to use.

    nowadays, I agree with you; with c++17 we finally even have inline variables, there's no 'language level' reason for using more than one TU. With older c++'s the matter is less evident ... anyway, I'm totally for deferring the cpp/h splitting in the learning process; knowning what a TU is should be a first class citizen and not just a 'routine' side effect

    that said, IMHO, for a general, scalable c++ project, h/cpp splitting ( when appropriate ) is still the most reasonable way of managing TU's and overall code orginization. But this is going off-topic so I'll stop here

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured