#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    32
    Rep Power
    11

    Need help writing a class


    Ok, some of you may recognize me. I've posted a couple times. I'm pretty new to c++ but i'm trying to learn! Here's my problem right now..

    I'm trying to create a class. I want this class to contain information like a persons first and last name, age and maybe addressn and phone. An address book was the best idea I could come up with to try to teach myself how to write classes. heh.

    I've found a couple tutorials online and so far, what i've read has just confused me. I don't want this to be a multiple record thing...yet. I want to keep it pretty simlpe. I just want to be able to keep one record that includes first, last, address and phone.

    Can anyone point me in the direction of a well written, easy to understand tutorial or can anyone help out with a little mini tutorial of their own?

    Thanks in advance, you always come through!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Location
    Austin TX yall
    Posts
    42
    Rep Power
    11
    just a quick resource that i found online that made my neck hurt.
    http://www.mcs.vuw.ac.nz/courses/COM...otes/lec04.pdf
    another great resource is to search for c++ tutorials on the major search engines. another great resource is universities. Sometimes you can find the lecture notes for a beginning c++ class. typically these are pretty thorough. Here's another..

    classes tut good luck and happy coding!
    Thanks,

    Jonathan Cobb
  4. #3
  5. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    ahh the power of boredom! here is a very simple program i wrote. hopefully you will find it useful and make it better :)

    Code:
    #include <stdio.h>
    #include <string.h>
    
    class person
    {
            /* these private members can only be accessed from functions in this class. this is known as
             * data encapsulation, it allows us to ensure the integrity of our data by providing functions
             * that get and set the data members    */
            private:
                    char    fname[20];      //first name
                    char    lname[24];      //last name
                    int     age;            // age!
    
            public:
                    person();       //this is the constructor; every time an object of the class is created
                                    //this function is called
                    ~person();      //this is the destructor; every time an object of the class is destroyed this is 
                                    //called. usually we use this to free dynamically allocated memory
            void    get_all(char *, char *, int &); //we use this method to get the values of our private data
                                    //members. usually you would have a get method for each member, but im simplifying :)
            int     set_all(char *, char *, int);   //this is how we set, once again simplified
            void    print();                //we use this to print the value of this objects data
    
    };
    
    person::person(){       printf("we made a person object!\n");   }
    person::~person(){      printf("we killed a person!\n");        }
    
    void person::get_all(char *pfname, char *plname, int &page)
    {
            strcpy(pfname, fname),  strcpy(plname, lname);
            page = age;
    }
    int person::set_all(char *pfname, char *plname, int page)
    {
            //usually you would want to verify the data b4 assigning it
            //so we would want to make sure page is actually a valid age for example
            if( (page < 0) || (page > 150) )
            {
                    printf("bad age!\n");
                    return -1;
            }
    
            strcpy(fname, pfname),  strcpy(lname, plname);
            age = page;
            return 1;       //return positive value for success
    }
    
    void person::print()
    {
            printf("\nHi, ny name is %s %s\nI am %d years old\n",
                            fname, lname, age);
    }
    
    int
    main()
    {
            char    *fname = new char[50],  *lname = new char[50];
            int     age = 0;
            person dummy;
    
            if( (dummy.set_all("Dirk", "Diggler", 240)) < 0 )       //lets give it a bad age
                    dummy.set_all("Dirk", "Diggler", 24);   //now a good one
    
            dummy.get_all(fname, lname, age);       //lets fill up our main variables with our objects data members
            dummy.print();                          //lets print out from the object
    
            printf("\nnow in main\n%s %s is a %d year old dummy\n",
                            fname, lname, age);     //now print from the main buffers
    
            //cleanup our memory allocated above
            delete fname;
            delete lname;
            return 0;
    }
    output:
    we made a person object!
    bad age!

    Hi, ny name is Dirk Diggler
    I am 24 years old

    now in main
    Dirk Diggler is a 24 year old dummy
    we killed a person!
  6. #4
  7. No Profile Picture
    status unknown
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    262
    Rep Power
    12
    Infamous41md,

    No offence, but that's a pretty poor example of C++ code. At best it's hybrid C/C++, but even then the C++ part is poor.

    > #include <stdio.h>
    > #include <string.h>
    These are standard but deprecated. Prefer the use of <cstdio> and <cstring> instead, if you must use C-style I/O and C-style strings, but better would be to use the C++ equivalents.

    > char fname[20]; //first name
    > char lname[24]; //last name
    > int age; // age!
    Instead of using cryptic code as an identifier, why not use something a little more meaningful, e.g.:

    char firstName[20];
    char lastName[24];
    int age;

    Note, no comments are now necessary. The purpose is clear, not just here (where you commented) but everywhere the names are used within the program.

    > person();
    > //this is the constructor; every time an object of the class
    > is created this function is called
    That depends on how the object is created, of course. Person objects can be created without calling this function at all.

    > int person::set_all(char *pfname, char *plname, int page)
    This function returns a value that represents one of only two possible states, success or failure. An obvious case for using a bool.

    > char *fname = new char[50], *lname = new char[50];
    > delete fname;
    > delete lname;
    Horrible. Should be:
    delete [] fname;
    delete [] lname;

    The following is a quick revision that is more in keeping with C++ style. No doubt it may be improved upon, but still:

    Code:
    #include <iostream>
    #include <string>
    
    class person
    {
    private:
        std::string firstName;
        std::string lastName;
        int age;
    public:
        person();
        ~person();
        void get_all(std::string& , std::string&, int&) const;
        bool set_all(const std::string&, const std::string&, const int);
        void print() const;
    };
    
    person::person()
    {       
        std::cout << "We made a person object!" << std::endl;
    }
    
    person::~person()
    {      
        std::cout << "We killed a person!" << std::endl;
    }
    
    void person::get_all(std::string& FirstName, std::string& LastName, int& Age) const
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
    
    bool person::set_all(const std::string& FirstName, const std::string& LastName, const int Age)
    {
        if((Age < 0) || (Age > 150) ){
            return false;
        }
        firstName = FirstName;
        lastName = LastName;
        age = Age;
        return true;
    }
    
    void person::print() const
    {
            std::cout << "Hi, my name is " << firstName << " " << lastName 
                      << " I am " << age << " years old" << std::endl;
    }
    
    int main()
    {
        std::string FirstName;
        std::string LastName;
        int Age = 0;
        
        person dummy;
        if(!dummy.set_all("Dirk", "Diggler", 240)){
            std::cout << "bad age!" << std::endl;
            dummy.set_all("Dirk", "Diggler", 24);
        }
    
        dummy.get_all(FirstName, LastName, Age);
        dummy.print();
    
        std::cout << "now in main " << FirstName << " " << LastName 
                  << " is a " << Age << " year old dummy" << std::endl;
    }
  8. #5
  9. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    LOL, guess it's pretty obvious i dont code in C++, yes? i donno man i was just bored and threw someting together. wasnt supposed to be some **** to base ur next class assignment on.
    but still...
    **firstName - this is just ur personal preference. if you can't realize what fname/lname stand for um, well no comment.
    **std::string - sorry i think the string classes are annoying. why do you feel the need to use them?
    **delete -yes i apologize i 4got about the correct way to do that. looking thru some notes i see u r right. thanks.
    **returning int instead of bool - yea... usually i just use u_char but i figured that would confuse him. bool woulda been correct as you said. as i said "...MAKE IT BETTER "
    **i have learned something here, how is one to create an object w/o invoking the constructor? looked thru my year old c++ notes and couldnt find anything about this, could u elaborate or provide me a link?
    **when and where was it ever stated that it mixing C/C++ is wrong? why wouldnt one want to take advantage of C++ while still also taking advantage of C? i've never heard anything like this b4.

    -but thanks for your comments i'm sure he'll appreciate them.
    Last edited by infamous41md; September 12th, 2003 at 05:29 PM.

IMN logo majestic logo threadwatch logo seochat tools logo