Thread: Need help in classes

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    12

    Question Need help in classes

    First I wanted to say that the tutorials in the site for C++ are great! They help alot

    and I wanted to ask a question, I got to the classes tutorial and I didn't understood it...
    Can someone explain me shortly a little about classes and then I will try to read again the tutorial, maybe I will understand it after I will know a little about them... thanks ahead

  2. #2
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    Classes.. at first they can seem a bit intimidating.. but hopefully I can give you some insight that will make classes easy.


    Q: What is a class?

    A: A class is a special block of code that is seperate from the rest of the program. A class will contain 2 things:

    • public class functions
    • private class variables


    A class is nothing more than a group of associated functions.. and the variables they manipulate throughout the program.

    In this example, let's say you are writing a simple bank account program. You will need to write functions to add to the account.. subract from the account.. and add an interest rate. Ok.. why not throw them all into a single class:


    example:

    Code:
    class Account
    {
    
    public:
    
          //Constructor
         Account( );
    
          //Setters
         void deposit(int);
         void withdrawals(int);
         void set_interest_rate(float);
         void add_interest( );
         
          //Getters
          int get_deposit( );
          int get_withdrawals( );
         
          //Constants
          bool is_overdrawn( ) const;
    
    private:
    
           int total_deposits;
           int total_withdrawals;
           int interest_rate;     
    
    };


    One major benefit to classes is code re-use. If you wanted to.. you could use the same class in other programs.

    Another benefit to classes.. is that only your class functions can have access to and can manipulate the class variables. This is really good when it comes restricting access to your variables.


    Q: How do I know if I need a class? And what stuff should I put in my class??

    A: Good question. Try this:

    You are going to write a program... and it's going to have a lot of functions.. and it's going to have a lot of variables. Go ahead and write your program without a class. When you are finished, you can go back and group your related functions and list their function prototypes into the public area of your class. Next, get all of the variables your class functions manipulate and list them in the private area of your class.
    Last edited by The Brain; 11-25-2004 at 10:20 AM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  3. #3
    Registered User
    Join Date
    Nov 2004
    Posts
    12
    First thanks alot, by what I understood the class is just like function that hold a piece of code that you can repeat it how much times you want instead of writing for the start always, only class is not to hold variables and codes but to hold the functions, for example if you call the same functions 5 times in a code in the same order then you can just do a class and then call the class, I understood right?
    and I still didn't understand something,
    First what is the constructor and destructor?
    and second if I have a function that contains the code:
    Code:
    int x;
    x=1;
    (just a small example)
    I can just put the x into the class private group and then in the function only write
    x=1;
    and I won't have to define the integer in the function?
    if yes then what does it help?

    and thanks again
    Last edited by LBY; 11-25-2004 at 07:28 AM.

  4. #4
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    class is just like function...
    Close.. but not quite

    A class actually takes on the role of a data type. For example, just like you would declare integer, float, double, bool etc.. you can declare an object of type 'Account'

    Code:
    Account savings;   //create a 'savings' object

    now you can do stuff like this:

    Code:
    //This will dereference and return total deposits from the 'savings' instance of the Account class:
    cout << "Your total deposits are: " << savings.get_deposits( ) << endl;


    So.. now that you know classes.. you now know how to create your own new data types.. a powerful aspect of object oriented programming.
    Last edited by The Brain; 11-25-2004 at 07:39 AM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  5. #5
    Registered User
    Join Date
    Nov 2004
    Posts
    12
    But can't you do the same thing with structures?
    You can write a structure and write inside variables and then do the same thing no? (sorry for asking alot questions)

  6. #6
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    I'm glad you asked.


    Although structs and classes are essentially the same... there are a couple of differences:

    by default, struct is set to public whereas class is set to private.

    according to modern coding conventions, structs are only to contain attributes (variables) whereas classes are to contain both functions and attributes.

    for example, nodes of a linked list are usually made of structs because they only contain data.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  7. #7
    Registered User
    Join Date
    Nov 2004
    Posts
    12
    Ok I think I understood it, I will read again now the tutorial to be sure and maybe one or two more things and finish with it, actually I expected the class to be something bigger because in the tutorials it start with saying that C++ have many small improvements for C and one major one (the classes) so I expected something bigger then just something that will contain variables and functions so you won't need to write them alot times...

    anyway thanks alot =]

    by the way I have a last question about it, in the functions when I want to use the same variable in the function from the code before and keep his value I write the variable in barckets "( )" when I define the function and call it, but if I use a class, can I just call the variable into the class and then I won't need to write again in every function that I want to use it? or do I still have to do it?

  8. #8
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Once you assign a value to a member variable of a class object it will remain the same value until you change it again. This is just like when you assign a value to an int or double or a string; the value stays the same, no matter where you use the object, unless you change it.


    The description of classes given by The Brain was simplified to allow you to start to work with classes on an introductory level. There is a lot more to classes than that however. For example, classes can have three levels of access for member, The Brain left out protected. New classes can be derived from earlier classes, something not possible with primitive data types like int, double, etc. Each derived class can derived using private, protected, or public inheritance. Inheritance need not be a one to one thing, that is a new class can be derived from more than one parent class, if you wish. Member functions of classes can be declared virtual, so you can use polymorphism, a powerful tool that you can learn about later. There's more too, but none of it is necessary to start working with classes, and it usually just get's you more confused if you try to learn it all at once. Learn the basics that The Brain talked about first, but be aware that once you have the basics under control there is a whole lot more that you can take advantage of, if you want.

  9. #9
    Registered User
    Join Date
    Nov 2004
    Posts
    12
    Ahh it seemed to me weird that what the brain told me is everything you need to know because it sounds like a big thing by the tutorials, anyway then you are right I will start with the basic then after I will be ready I will ask in the forum to tell me about more or read tutorials about it...
    Ok I understood what I wanted to, thanks for helping (I still didn't understand the Constructor and Destructor but never mind I don't think I will be using this classes soon, when I will want to find out about it more then I will just ask)

  10. #10
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    constructors are specialized class methods whose job is to instantiate objects of the class type with initial values of the data members. Constructors can have a variety of arguments passed to them, but no construcors have a return type, not even void. Constructors that take no parameters are called default constructors. Constructors that create one object of the class by copying the data from another object of the class is called a copy constructor. You can create other constructors as needed, for example, constructors that take one or more parameters whose values will be assigned to data members of the class as the initial values for the class member(s). Each class should have a default constructor and a copy constructor, and if you don't declare any constructors explicitly, the compiler will create default versions of a default constructor and copy constructor for you. However, it is better if you do it. You should be aware that if you do explicitly create a constructor, then the compiler won't create any default versions of either the default constructor or the copy constructor.

    Likewise, every class must have a destructor as well. If you don't define it explicitly, the compiler will do it for you, but it's better if you do it. The primary job of the destructor is to release any dynamic memory that has been declared by the class methods, if it hasn't already been released by the time the destructor is called. However, other tasks can be assigned to the destructor as well. Like constructors, destructors have no return type, but unlike constructors, I've never seen a class with more than one destructor, though I don't know if there is rule against that or not.

    Despite all this work, you will (almost) never explicitly call a constructor or a destructor within your code. The compiler will call them for you based on the code you write.

    Below is an untested/uncompiled version of a simple Student class. It has a default constructor, a non-default constructor, a copy constructor, a destructor, and two data members. The default constructor initializes age to zero and gender to a default value of * within the body of the constructor. The prefered way, however, is to initialize members using an initialization list as in the non-default constructor. The copy constructor copies the value of age and gender in rhs into the new Student object. The destructor is just given an inane statement to show you that it is used, even though the code doesn't call it. In the body of main() I've declared three Student objects, Judy using the default constructor, Sally using the non-default constructor, and Mary using the copy constructor making Mary a copy of Sally (identical twin?). To prove that the cosntructors are called by the compiler eventhough they aren't called explicitly I've provided public accessor functions to demonstrate that the data members have been initialized as expected. Since I haven't provided any public mutators, the data members will never be changed throughout the course of the program. This may or may not be the desired state of affairs in any given program for any given member.
    Code:
    class Student
    {
    public:
    	 Student();
    	 Student(int, char);
    	 Student(const Student &);
    	 ~Student();
    	 int getAge() const;
    	 char getGender() const;
    private:
    	 int age;
    	 char gender;
    };
     
    Student::Student()
    {
      int = 0;
      char = '*';
    }
     
    Student::Student(int i, char c) : age(i), gender(c) 
    {}
     
    Student::Student(const Student & rhs)
    {
      age = rhs.age;
      gender = rhs.gender;
    }
     
    ~Student::Student {cout << "destructor called" << endl;}
     
    int Student::getAge() const {return age;}
    char Student::getGender() const {return gender;}
     
    int main()
    {
      Student Judy();
      Student Sally(18, 'f');
      cout << Judy.getAge() << ' ' << Judy.getGender() << endl;
      cout << Sally.getAge() << ' ' << Sally.getGender() << endl;
     
      Student Mary(Sally);
      cout << Mary.getAge() << ' ' << Mary.getGender();
    }
    Last edited by elad; 11-25-2004 at 06:16 PM.

  11. #11
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Despite all this work, you will (almost) never explicitly call a constructor or a destructor
    within your code. The compiler will call them for you based on the code you write.
    This depends entirely on how your program approaches memory management.

  12. #12
    Registered User
    Join Date
    Nov 2004
    Posts
    12
    Ok I think I understood it know, thanks alot!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you Initialize all classes once with New?
    By peacerosetx in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2008, 10:47 AM
  2. Multiple Inheritance - Size of Classes?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 11-26-2004, 09:04 AM
  3. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  4. Exporting VC++ classes for use with VB
    By Helix in forum Windows Programming
    Replies: 2
    Last Post: 12-29-2003, 05:38 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM