CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: Classes...

  1. #1
    Join Date
    May 2011
    Posts
    2

    Smile Classes...

    Hi everyone, I've been learning C++ for just under a week now, and I understand most of the basics, except pointers and classes. Classes seem more essential so can anybody explain them to me? I've read countless tutorials that don't explain them well, it just won't sink in.

  2. #2
    Join Date
    Jul 2010
    Posts
    94

    Re: Classes...

    {Class} is divided into abstract and concrete types.Abstract class is used as a base class, so it is called abstract base class. in C++, people use virtual keyword to make a class abstract to inherit from. An abstract base class without implementation is called an interface in Java sense. A concrete class is one your client code will use and is also the one derived from its ancestor abc. An ancestor class will give rise to a base object and the child class will produce a derived object. Class to class relation in C++ is called inheritance that can be public, protected or private, people call it inheritance hierachy.


    Kkakakkaak

  3. #3
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Classes...

    Bookstores and the internet are full of definitions and explanations of classes. I doubt anybody here can explain any better than what's out there. Do you have any specific questions?

  4. #4
    Join Date
    May 2011
    Posts
    2

    Re: Classes...

    I've read up loads, but there's nothing that will sink in. It just goes straight over my head. I don't see the need for them or pointers, I can't see how they would be useful.

  5. #5
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Classes...

    Quote Originally Posted by InjexDnB View Post
    I've read up loads, but there's nothing that will sink in. It just goes straight over my head. I don't see the need for them or pointers, I can't see how they would be useful.
    You need to get a good tutorial and start working with them. C++ has a pretty steep learning curve. A week isn't much time for anything substantial to sink in.

    Basically classes are used to model real-world objects or concepts in your program. Just as with most things, they have attributes and behaviors that your program can manipulate and execute.

  6. #6
    Join Date
    Jun 2008
    Posts
    592

    Re: Classes...

    pointers are more fundamental than classes are because classes can rely on pointers..... If you understand most of the basics, you should be able to learn pointers quick enough.

    http://www.cplusplus.com/doc/tutorial/pointers/

    classes in c++ is not easy work. You have a lot of requirements to think about when dealing with them. A quick warning... never use global classes before main...

    http://www.cplusplus.com/doc/tutorial/classes/

    Also copy, paste and run the examples through the debugger step by step.

    Quote Originally Posted by Sharpie
    people use virtual keyword to make a class abstract to inherit from.
    Yep and they also make an inheritance virtual http://en.wikipedia.org/wiki/Virtual_inheritance
    A good trick with inheriting a virtual non-abstract class would be to allow common code to rely on a common class even if that common class was to be inherited by another class that is also being inherited. It won't complain since there is no multiple copies of that common class. I have personally done this to reduce common code... That is how I came by virtual inheritance...

    Code:
    class cHwnd
    {
    protected:
        HWND hwnd;
    };
    
    class cMovable : virtual cHwnd
    {
    public:
        void Move( int x, int y )
        {
            MoveWindow( hwnd, x, y ); // os specific command
        }
    };
    
    class cShowable: virtual cHwnd
    {
    public:
        void Show()
        {
            ShowWindow( hwnd ); // os specific command
        }
    
        void Hide()
        {
            HideWindow( hwnd ); // os specific command
        }
    };
    
    class cWindow : public cMovable, public cShowable, virtual cHwnd
    {
    };
    
    class cChildObject : protected cHwnd
    {
    protected:
        cWindow& Window;
    public:
        cChildObject( cWindow& Window ) : Window( Window )
        {
    
        }
    };
    
    class cButton : public cMovable, public cShowable, private cChildObject
    {
    public:
        cButton( cWindow& Window ) : cChildObject( Window )
        {
        }
    };
    
    class cTextBox : public cMovable, public cShowable, private cChildObject
    {
    public:
        cTextBox ( cWindow& Window ) : cChildObject( Window )
        {
        }
    };
    c++ has been explained over and over again. It also has a standard you can read.
    GCDEF is right. You can't expect to learn c++ over week or even a month. Perhaps a year to get an average grasp of c++. Results may vary...

    Try to code real examples.... and you will see why
    Last edited by Joeman; May 25th, 2011 at 12:41 PM.
    0100 0111 0110 1111 0110 0100 0010 0000 0110 1001 0111 0011 0010 0000 0110 0110 0110 1111 0111 0010
    0110 0101 0111 0110 0110 0101 0111 0010 0010 0001 0010 0001 0000 0000 0000 0000
    0000 0000 0000 0000

  7. #7
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Classes...

    Quote Originally Posted by InjexDnB View Post
    I've read up loads, but there's nothing that will sink in. It just goes straight over my head. I don't see the need for them or pointers, I can't see how they would be useful.
    Classes are primarily used to aid in abstraction. Working directly with primitive types is fine for trivial programs, but as your code increases in complexity, it is helpful to compartmentalize. If you have a need to, for instance, maintain a garden numerous times in your code, you could simply write all of the code to maintain the garden everywhere you want to do it. That's a lot of extra work, however. A better option would be to write a maintain_garden() function and just call it wherever you like.

    However, in some cases that still isn't good enough. Let's say that how you maintain a garden depends on how many seeds you have left and what month it is. Function parameters? Sure. But you still need to carry about that knowledge to everywhere the function is going to be called. So why not bundle up the knowledge along with the function itself? Global variables are of course discouraged, so designing a Gardener class may be the best option.

    The Gardener class could have a num_seeds member and a maintain() method. So you could write:
    Code:
    Garden mygarden;
    Gardener bob;
    
    bob.maintain(mygarden);
    Here Garden may also be a class (or a struct, they're largely identical).

    This becomes even more powerful when you realize that you can have multiple different Gardener objects which will each track their own remaining seeds and multiple different Garden objects each with some state of their own, and you can mix and match which Gardener maintains each Garden as much as you like.

    As for pointers, we'll worry about those once the utility of classes sinks in.

  8. #8
    Join Date
    May 2011
    Posts
    18

    Re: Classes...

    I too have been learning c++ for about 3 weeks now and I'm having some trouble with classes.

    I think I have the basics of Public and Private down, but I do have a few specific questions.

    Is it possible to call a Public Variable or Public Function(which contains public variables) from outside of main & the Class, in a function that is defined as such: void Classname::Example() ?
    -- I can only get it to work in functions defined as above if they don't include the public variables or public calls. I also have created the object name as Cassname e; and use the variables or functions called as e.playername; or e.playerattack(); but this doesn't seem to work. I know I must be missing something. As a workaround, I've just been defining and using the public functions inside of the Class. I'm starting to wonder if class variables/functions can only be called from inside of Main.

    I have been able to gain the understanding of how to use private variables and use public functions to return the private variable into a public variable. I understand this is good for security and such.

    To the guy that has only been learning for a week, I recommend doing the following:
    1) Buy an actual book that you can look at and learn from, do the examples.
    2) When doing tutorials that provide code, type it out and and put comments in it based on what they are telling you in the tutorial.
    3) Get a paper spiral notebook and write code in it with a pencil, and copy code from working program, and code examples to help you learn the syntax.

    Classes are really confusing for me to, but I just now feel like I'm starting to get some use out of them, and some solid understanding. In case you didn't already know, Classes let you make your own type instead of making a variable or function as int, void, string, float; you can make up your own type and name it, then you can created type your created name instead of the default ones so you know more what you are looking at, and you can also make the program more secure and easy to debug by doing this instead of using global variables and functions. (as far as my understanding goes)

  9. #9
    Join Date
    Apr 2011
    Posts
    18

    Re: Classes...

    Read Scott Mayer's books please.
    He writes awesome items and explains things in details from basic to higher levels.

  10. #10
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Classes...

    Quote Originally Posted by Jayzan View Post
    Is it possible to call a Public Variable or Public Function(which contains public variables) from outside of main & the Class, in a function that is defined as such: void Classname::Example() ?
    -- I can only get it to work in functions defined as above if they don't include the public variables or public calls. I also have created the object name as Cassname e; and use the variables or functions called as e.playername; or e.playerattack(); but this doesn't seem to work. I know I must be missing something. As a workaround, I've just been defining and using the public functions inside of the Class. I'm starting to wonder if class variables/functions can only be called from inside of Main.
    You'll have to show the code you're trying and the errors it is generating.

    Classes let you make your own type instead of making a variable or function as int, void, string, float;
    In fact, std::string *is* a class defined in the standard library. It was created to replace the old "C" approach of using char arrays to handle string data, because that is both more difficult and more error-prone. So that's a good example of how to use classes well: wrap up the "difficult" code in a simple and intuitive interface, so that you only have to get it right once.

  11. #11
    Join Date
    May 2011
    Posts
    18

    Re: Classes...

    I'll make an example program and post it and the errors as soon as I can.

    Thanks =)

  12. #12
    Join Date
    May 2011
    Posts
    18

    Unhappy Re: Classes...

    Ok, here is a portion of the code that i'm working on. At the very bottom the error is listed as a comment. This code works if you put comment slashes in front of the very last 3 lines of code. Why is it giving me this scope error? Is there a way to remedy this without putting the function definition in the Public portion of the class at the top, or without defining it in main? Thanks for any help provided!

    // Text Based RPG Game

    #include <iostream>
    #include <ctime>
    #include <cstdlib>
    #include <windows.h>
    #include <string>

    using namespace std;

    class TextBasedRPG
    {
    public: // PUBLIC VARIABLES::
    string playername;
    string answer;
    string gender;
    int age, hp, mp, dmg, currentLoc, zDmg, zHp;
    bool DEATH, magic;
    void intro(); // DECLARES FUNCTIONS ****************************
    void road();

    private: // PRIVATE VARIABLES:
    //******* define private variables ***************
    string name, yesNo, sex;
    //****** end define private variables*************

    public: // PUBLIC FUNCTIONS:///////////////////////////////////////////////////////////////////////////////////////////

    string getName() // This is a public function that returns the value in the private string variable 'name'.
    {
    std::cin >> name;
    playername = name;
    return name; // This is private and can't be access by main
    }

    string getSex()
    {
    std:cin >> sex;
    gender = sex;
    return sex;
    }

    string getAnswer() // This Function gets input from the user and uses the setAnswer to set the private variable to the public variable.
    {
    std::cin >> yesNo;
    setAnswer();
    return answer;
    }
    void setAnswer() // This is a public function that is a SETTER all it does is make the value of the private variable availble in public
    {
    answer = yesNo; // This is a Setter Function to get the Private name varible accessible in main()
    }

    void findName()
    {
    cout << "What shall the people of this land call thee?\n";
    cout << "[ENTER YOUR DESIRED NAME]";
    Sleep(500); //////////////////////////////////////////////////////////
    getName();
    Sleep(300); //////////// slight pause to slow down game **************
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(300); //////////////////////////////////////////////////////////
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(300); //////////////////////////////////////////////////////////
    cout << ".\n"; ///////////////////////////////////////////////////////
    Sleep(300); //////////// slight pause to slow down game **************
    cout << "Do you wish to be called ";
    cout << playername << "?\n";
    cout << "[ENTER yes OR no]:";
    getAnswer();
    if (answer == "yes")
    {
    Sleep(300); //////////// slight pause to slow down game **************
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(300); //////////////////////////////////////////////////////////
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(300); //////////////////////////////////////////////////////////
    cout << ".\n"; ///////////////////////////////////////////////////////
    Sleep(300); //////////// slight pause to slow down game **************
    cout << "Then on with the game!\n";
    Sleep(350); //////////////////////////////////////////////////////////
    }
    else
    {
    getName();
    }
    } //**************************END GET NAME MEMBER FUNCTION***********************

    void getGender() //**************** GENDER FUNCTION **********************
    {
    system ("CLS");
    Sleep(500); //////////////////////////////////////////////////////////
    cout << "What gender shall you be?\n";
    Sleep(500); //////////////////////////////////////////////////////////
    cout << "[TYPE man OR woman]: ";
    getSex();
    Sleep(500); //////////////////////////////////////////////////////////
    cout << "Do you wish to be a ";
    cout << gender << "?\n";
    Sleep(500); //////////////////////////////////////////////////////////
    cout << "[ENTER yes OR no]: ";
    Sleep(500); //////////////////////////////////////////////////////////
    getAnswer();
    if (answer == "yes")
    {
    Sleep(500); //////////// slight pause to slow down game **************
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(500); //////////////////////////////////////////////////////////
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(500); //////////////////////////////////////////////////////////
    cout << ".\n"; ///////////////////////////////////////////////////////
    Sleep(500); //////////// slight pause to slow down game **************
    cout << "And a fine ";
    cout << gender << " you will be!\n";
    }
    else
    {
    getGender();
    }
    } //******************************* END OF GENDER FUNCTION ****************************
    };

    // ##################################################################################
    int main() //******* MAIN FUNCTION OF ENTIRE PROGRAM ********************************
    {
    TextBasedRPG e; // Creates the Class Object for use as prefix on function and variable calls inside of main.
    e.intro();
    e.findName();
    e.getGender();
    e.road();
    return 0;
    } // ********************** END MAIN FUNCTION **************************************
    // ##################################################################################

    // Function #1 for Introduction to world
    void TextBasedRPG::intro()
    {
    system ("CLS");
    Sleep(500); //////////// slight pause to slow down game **************
    cout << "Loading Game."; /////////////////////////////////////////////////////////
    Sleep(500); //////////// slight pause to slow down game **************
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(500); //////////////////////////////////////////////////////////
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(500); //////////////////////////////////////////////////////////
    cout << ".\n"; ///////////////////////////////////////////////////////
    Sleep(500); //////////// slight pause to slow down game **************
    cout << "Welcome to the world of TextBasedRPG. \n";
    Sleep(500); //////////// slight pause to slow down game **************
    cout << "Before you enter this strange new world you must give your name. \n";
    Sleep(500); //////////// slight pause to slow down game **************
    }

    void TextBasedRPG::road() // Road Function **************************8
    {
    // This is the road, path, trail, travelling system function
    Sleep(500); //////////// slight pause to slow down game **************
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(500); //////////////////////////////////////////////////////////
    cout << "."; /////////////////////////////////////////////////////////
    Sleep(500); //////////////////////////////////////////////////////////
    cout << ".\n"; ///////////////////////////////////////////////////////
    Sleep(500); //////////// slight pause to slow down game **************
    cout << "You are on a road that leads north to south.\n";
    Sleep(500); //////////////////////////////////////////////////////////
    Sleep(750); //////////////////////////////////////////////////////////
    cout << "There is forest on the East.\n";
    Sleep(1000); //////////////////////////////////////////////////////////
    cout << "And there is a grassy field on the West," << e.playername << "\n";
    Sleep(600); //////////////////////////////////////////////////////////
    e.road(); // this will eventually call an encounter function.
    }

    // ######################{{{{ ERROR WHEN RUN IS BELOW:
    // example.cpp: In member function 'void TextBasedRPG::road()':
    // example.cpp:181:55 error: 'e' was not declared in this scope
    // NOTE: This error occurs for the first instance of "e" that is called no matter how many occurances in the function.
    // If you make those two lines a comment with the "//" the program runs fine

  13. #13
    Join Date
    Mar 2011
    Location
    Delhi India
    Posts
    110

    Re: Classes...

    except pointers and classes
    These two thing are important it is seeming that you leave pointer dear read it. Yes they come in toughest part of C++ but if you will try then you will. I have studied little on pointer in a sentence you can say that it is address of the data you can make better control on your data using pointer.
    And classes i don't think starting of class is difficult till now you must know [font=courier]integer(int), character(char)[font] etc but class give you opportunity to make your own data types. Inheritance is harder.
    my tip to you is to buy a good book of C++ and start learning from only one platform(one book). Use internet for further help
    I think one of these two books.(I am not advertising)
    teach yourself C++ in 21 days (latest edition)
    Beginning visual C++ 2010 by Ivor Horton.
    there are many other good books but i did not know their names.
    Last edited by vkash; May 26th, 2011 at 04:57 AM.

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

    Re: Classes...

    Quote Originally Posted by Jayzan View Post
    Ok, here is a portion of the code that i'm working on.
    Please, look at this your post and tell us (but honestly!): is it easy to read/understand this code snippet?
    For me it is absolutely unreadable! To make it readable you have to use Code tags. See Announcement: Before you post....
    Victor Nijegorodov

  15. #15
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Classes...

    Code:
    void TextBasedRPG::road() 
    {
        e.road(); // this will eventually call an encounter function.
    }
    Two problems here. First, there is no object called "e" in this function, which is what the compiler is telling you. However, you are already within the object called "e" in main, since the road() method was called on that object. So you could just call road() again directly unless you actually did want to call the road() method of a different TextBasedRPG object.

    HOWEVER. Doing this would make the road() method recursive, which means that it would be continually calling itself (unconditionally) forever. This is very, very bad, and will probably lead to a crash in short order when you run out of stack space.

    Most likely what you intended was to call road multiple times in a row until something happened. For that, you're better off using a loop.

Page 1 of 2 12 LastLast

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