Class questions!

This is a discussion on Class questions! within the C++ Programming forums, part of the General Programming Boards category; I just have a couple questions concerning classes. 1. Can you have multiple classes in one file? as in #ifndef...#endif ...

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    51

    Class questions!

    I just have a couple questions concerning classes.

    1. Can you have multiple classes in one file? as in #ifndef...#endif then another #ifndef...

    2. does the file name have to be the same as the class name? aka circle.h and the file has to be circle?

    3. Do classes only handle data? Can the member functions cout stuff to the screen and get input?

    4.What exactly does a constructor do? Like lets say you want to house a constructor for a house, would you have to set all the variables there to zero

    Code:
    public:
    house();
    
    private:
    float doors, windows, rooms;
    
    house::house()
    {
    doors=0;
    windows=0;
    rooms=0;
    }
    5. Can someone please explain to me what this "copy constructor" does because I have no clue on that

    Code:
    public:
              circle();
              circle(const circle &);<-copy constructor
    private:
              ....
    
    circle::circle(const circle & Object)<-Dont know what object exactly does
    {
    radius=object.radius;
    }
    Tell me if you need the entire coding for the copy constructor but yea thanks for reading all my questions
    Last edited by Shadowwoelf; 01-19-2007 at 06:16 PM.

  2. #2
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    1) Yes, but not sure what you mean by the preprocessor stuff. Here's two classes, in one header file:
    Code:
    #ifndef MYHEADER_H
    #define MYHEADER_H
    
    class ClassA
    {
       // members, blah
    public:
       ClassA();
       ~ClassA();
       // etc.
    };
    
    class ClassB
    {
       // etc.
    };
    
    #endif
    2.) Since you can put more than one class in a file, nope - class names do not have to match filenames. They often do for organizational sake, however.
    3.) Yes, a class can certainly cout, send stuff to a screen, printer, file, etc. (And sometimes classes encapsulate those objects)
    4.) A constructor initializes the members of a class. This can be to some default value, or to some value based on a passed argument.
    5.) A copy constructor is just a special type of constructor. You should read a couple tutorials for your answers to 4 & 5. See this site's tutorial for starters, Lesson 12 is on construtors. (Google is also great.)
    Last edited by Cactus_Hugger; 01-19-2007 at 06:36 PM.
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    1. Yes, although you don't need multiple #ifndef (called header include guards). Just one set per header file is fine. Those guards should surround the entire header, including all classes declared inside.

    2. No. That is a general convention, though. You should make your header names meaningful and let them give an idea of what is inside. Since people often put one class inside a single header, naming the header file after the class makes sense.

    3. Member functions can do many different things, including using cout or getting input. Some classes are not designed to hold data at all, they are designed only to perform actions. There are many different reasons to create a class, it is just that the most basic and easy to understand uses are modeling objects with data.

    4. A construct initializes the object. So setting the member variables to 0 is a good thing to do in a constructor. In your case, you would actually want to use an initializer list, which is a part of the construct that sets the initial value of member variables and base classes:
    Code:
    house::house() : doors(0.0f), windows(0.0f), rooms(0.0f)
    {
    }
    Note that I used 0.0f there because 0 is an int, 0.0 is a double and 0.0f is a float.

    5. A copy constructor initializes an object with data from a different copy. In many cases, you won't need to write a copy constructor for a class because the data will be copied correctly. For example, the radius is probably an int or double and so it will be copied automatically. The copy constructor is generally used for more complex classes that share resources like memory so that there are no conflicts with who owns the resource and who will release it. In this code:
    Code:
    int i = 5;
    int j = i;
    you can imagine that j is "constructed" with a copy of i's value. With built-in types like int, there really isn't any constructor calls, but the idea is the same. If you had variables of a class type instead of int in that example, then the copy constructor would be called to create j.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,157
    Quote Originally Posted by Shadowwoelf
    1. Can you have multiple classes in one file? as in #ifndef...#endif then another #ifndef...
    Yes. There is no rule preventing a header file from declaring multiple classes, a source file from implementing multiple classes.

    In fact, there is technically no mandate that a project will use header files at all. Such things are a convention. Albeit a convention that is often applied.

    In practice, people will tend to be able to maintain code better if the project is systematically broken into chunks (eg one header file that declares a class and one source file that implements its member functions). Which means it is often a good idea to do that to avoid driving team members crazy.
    Quote Originally Posted by Shadowwoelf
    2. does the file name have to be the same as the class name? aka circle.h and the file has to be circle?
    Nope. There is technically nothing stopping a programmer from declaring a class named circle in a header file named "square.h" and implementing its member functions in a source file named "triangle.cpp". Except the impact that will have by driving other programmers crazy (or yourself if you have to maintain the code after a break of a couple of years).

    In a professional setting, your pay or continuing employment prospects will often be linked to performance, and team leaders will tend to frown on such things being done for no good reason, and view them as poor performance. So, if you are going to do such things, make sure that it makes sense to the team.

    If you are writing code for yourself, it is probably a good idea to be systematic about how you do things. After all, it does help if you can actually understand what you have done.
    Quote Originally Posted by Shadowwoelf
    3. Do classes only handle data? Can the member functions cout stuff to the screen and get input?
    Member functions can do anything you like.
    Quote Originally Posted by Shadowwoelf
    4.What exactly does a constructor do? Like lets say you want to house a constructor for a house, would you have to set all the variables there to zero
    To understand that, you need to understand that there are two phases in construction of an object. The first is getting raw memory (everything that contains data is raw memory as far as a computer is concerned) and the second is turning that raw memory into something that a human will call an "object".

    A constructor is a special function that the compiler invokes to turn the raw memory into an "object". After the constructor has finished, the object will exist. Typically the constructor initialises data members of the class instance to some sensible values that make sense for that class.
    Quote Originally Posted by Shadowwoelf
    5. Can someone please explain to me what this "copy constructor" does because I have no clue on that
    A copy constructor is a constructor that is invoked when creating a copy of an object that already exists. Let's say you have;
    Code:
    //  appropriate declarations of circle class
    
    int main()
    {
          circle a;
            // set radius of a to be something
          circle b(a)
    }
    then the circle b is a new object which is a copy of a (will have the same radius). If you subsequently change a, b does not change (i.e. they are different objects).

    The copy constructor is invoked in the process of creating b. It needs to receive information about a to be able to copy it.
    Quote Originally Posted by Shadowwoelf
    Code:
    public:
              circle();
              circle(const circle &);<-copy constructor
    private:
              ....
    
    circle::circle(const circle & Object)<-Dont know what object exactly does
    {
    radius=object.radius;
    }
    This (other than typos: Object should be object) is a copy constructor. The argument object, in my little example above, is a reference to a. The line "radius = object.radius;" effectively sets b.radius to be equal to a.radius.

    Quote Originally Posted by Shadowwoelf
    Tell me if you need the entire coding for the copy constructor but yea thanks for reading all my questions
    Depends on what you mean by "entire coding". A copy constructor (like any constructor) should correctly initialise the object being created. Otherwise code which works on that object (including other member functions) cannot work correctly if they assume the object is correctly initialised.

    Copy constructors are special though: if you don't provide one, the compiler will usually provide one for you. The default is a member-wise copy of the object being copied. If that default behaviour does not work correctly (and the notion of correctly is up to the programmer) then the programmer needs to explicitly supply one that copies the object correctly.

    In your example, you would probably not need to supply a copy constructor as the compiler-generated version will work correctly.

    A common example where it is necessary to hand-roll a copy constructor is if dynamic memory is managed.
    Code:
    class X
    {
        public:
            X() : x(new int [10])
            {
                for (int i = 0; i < 10; ++i) x[i] = i;
            };
    
            ~X() {delete [] x;};
        private:
            int *x;
    }
    With this class, the code;
    Code:
    int main()
    {
         X a;
         X b(a);
    }
    exhibits undefined behaviour (a crash as the program exits is a common symptom) as the compiler-supplied copy constructor will make a.x and b.x point to the same memory, and that memory will get deleted twice. This can be fixed by explicitly coding a copy constructor
    Code:
    class X
    {
        public:
            X() : x(new int [10])
            {
                for (int i = 0; i < 10; ++i) x[i] = i;
            };
    
            X(const X&a) : x(new int[10])
            {
                for (int i = 0; i < 10; ++i) x[i] = a.x[i];
            };         
    
            ~X() {delete [] x;};
        private:
            int *x;
    }

  5. #5
    Registered User
    Join Date
    Dec 2006
    Posts
    51
    Oh okay thanks for the answeres

  6. #6
    Registered User
    Join Date
    Dec 2006
    Posts
    51
    *Sorry for double posting I just didn't want to make another thread with the same title etc.*

    Ive got some more questions I just found recently

    1.How would I compile a class.h file with microsoft visual C++. Or do I not compile it?

    2.
    Code:
    #include <iostream> //for cout statements
    #include <stdio.h>//For random number thingy
    #include <stdlib.h>
    #include <time.h>
    #include <windows.h>
    using namespace std;//I know that I shouldn't use namespace but this is a test
    
    #ifndef _Craps_H
    #define _Craps_H
    Is that how you would add those files to the class?

    3.In the private part of the class you initilaze ALL the variables that you will use for in that entire class

    4.If I want to resend one variable back to the main program would I simply just have to add that variable to public?

    Thanks for reading this again...

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    How would I compile a class.h file with microsoft visual C++. Or do I not compile it?
    You don't compile .h files, you include them. Then the compiler will replace the include statement with the contents of the specified file. If the file contains only declarations of classes, something called "the linker" will go looking for the definitions of the class functions in your .cpp files and compile them automatically.

    Is that how you would those files to the class?
    Is that Spanglish?

    3.In the private part of the class you initilaze ALL the variables that you will use for in that entire class
    No. You initialize all member variables in a constructor, which is typically in the public section.

    4.If I want to resend one variable back to the main program would I simply just have to add that variable to public?
    Sending a value to a function or returning a value from a function has nothing to do with a class definition or the public access specifier.
    Last edited by 7stud; 01-21-2007 at 10:06 PM.

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    2. I would put the #includes and using directive inside the header include guards, but it is unlikely to matter much. Also, don't use leading underscores in your include guard names (even though many examples show this). A leading underscore followed by an uppercase letter is reserved for the implementation. Also, #defines are by convention placed in all capital letters. So in your case I would use CRAPS_H instead of _Craps_H.

    3. In general, member variables should be declared in the private section because this is better design by separating the implemention from the interface. Initialization should be done in the constructors as shown earlier.

    4. If you need the value of a member variable of a class in main, then your class should have a member function that provides access to that variable. For example, a circle class might have a radius member variable that is private, and a GetRadius() member function that is public. It might also have a GetArea() member function that is public that calculates the area from the private radius member variable.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Class design problem
    By h3ro in forum C++ Programming
    Replies: 10
    Last Post: 12-19-2008, 08:10 AM
  2. Replies: 8
    Last Post: 10-02-2005, 12:27 AM
  3. Class Questions
    By shane1985 in forum C++ Programming
    Replies: 7
    Last Post: 10-29-2003, 09:34 AM
  4. Series of class questions #1
    By kippwinger in forum C++ Programming
    Replies: 4
    Last Post: 10-02-2003, 04:28 AM
  5. class member access denied
    By chiqui in forum C++ Programming
    Replies: 2
    Last Post: 05-27-2002, 02:02 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21