Classes in a .h file

This is a discussion on Classes in a .h file within the C++ Programming forums, part of the General Programming Boards category; Hullo hullo I've just got a quick question about classes, and I ask you to bear with me cause this ...

  1. #1
    Epo
    Epo is offline
    Registered User
    Join Date
    Jun 2003
    Posts
    361

    Classes in a .h file

    Hullo hullo

    I've just got a quick question about classes, and I ask you to bear with me cause this is the first time I'm trying to learn about them

    Here's some sample code:
    Code:
    TheClass.h
    Class MyClass
    {
    public:
    InitialiseX(int Number);
    private:
    int x;
    };
    
    
    TheCode.cpp
    include "TheClass.h"
    
    MyClass::InitialiseX(int Number)
    {
    x = Number;
    }
    Now, I realise that there may be better ways to right such code, but here's what I'm wondering about...
    1) First of all, are there any errors in what I wrote up there?
    2) Can I use "MyClass.x ="
    3) My main question, can I move the "MyClass::InitialiseX" function dealey into the .h file? That way, it's a tad more organized. If so, are there any drawbacks to this?

    Thanks for any insight

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,505
    > 1) First of all, are there any errors in what I wrote up there?
    Seems OK to me

    > 2) Can I use "MyClass.x ="
    No, x is a private variable of the class, which means only functions of the class can access or change it.

    This is a cornerstone of OO, where data is encapsulated within the class and hidden from the rest of the world.
    This means you always have control over how your internal data is accessed and changed.
    It also permits you to change the implementation (say you change int x; to string x;) and the rest of the world need know nothing about that, since InitialiseX() has not changed.

    > 3) My main question, can I move the "MyClass::InitialiseX" function dealey into the .h file?
    Bad idea, for several reasons
    1. You would only be able to include that in ONE .cpp file of your project. This makes it less useful.
    The reason being that you would end up with multiple copies of the same code in your executable, and with identical names. The linker would reject this with multiple symbol errors.
    2. The interface to your class is the .h file, so you really don't want to be showing how you implemented the inside of the class, just in case someone feels tempted to try something sneaky.
    3. The amount of code within a class can be considerable, which would lead to some very bulky header files.
    4. If you give your class to someone else, you typically hand over class.h and class.lib (class.lib is the compiled version of class.cpp).

    The only time you include real source code inside a header file is if you make that function an inline function. For various reasons, you only want to do that for short functions (typically a couple of lines) which are called very often (say thousands of times per second).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    1) Not that I can see... A compiler would be able to give you a more definitive answer.

    2) No. The variable 'x' belongs to a specific instance of 'MyClass', and not to the class itself. You can, however, use 'this->x' in non-static member functions, though there is no point as 'x' would do the same thing from within the class.

    *edit*
    Misinterpreted the second question, I think. If you meant accessing it from outside the class, then no for the reason Salem mentioned. If you meant accessing it from inside the class, then no for the reason I mentioned.

    3) Yes, but I would advise against it. In a large project, you can modify your source file, without touching the header file (e.g. to change internal algorithms), and then you would only have to recompile that unit, and relink, instead of recompiling everything that includes your header. The exception is that many compilers require templated functions/classes to be declared and defined in the same file.
    Last edited by Zach L.; 12-24-2003 at 11:15 AM.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    1,203
    In answer to 1:
    Code:
    class MyClass
    {
    public:
        InitialiseX(int Number);
    private:
        int x;
    };
    
    // Needs to be
    class MyClass
    {
    public:
        void InitialiseX(int Number);  // Notice that you need a return type
    // Edit: I just checked and it seems like you dont HAVE to have a return type
    // But its still good to have one :)
    private:
        int x;
    };
    
    void MyClass::InitialiseX(int Number) //Make sure this has the right return type as well
    {
        x = Number;
    }
    For Q 2: You cant use something like
    Code:
    MyClass bla;
    bla.x=5;
    because you said that x should be private, and therefore only MyClass members can access this and all variables should be kept private, use access functions for them instead.

    As for question 3, I think you can have the definition of class-functions in a .h file and then just include that, but Im not sure at all why that isnt good, maybe it has something to do with that you dont compile the definitions...I dunno but its possible (I think).

    Also another tip: Indent the code, like I did with your code up there, it will make it so much easier to read.
    Last edited by Shakti; 12-24-2003 at 11:16 AM.

  5. #5
    Registered User glUser3f's Avatar
    Join Date
    Aug 2003
    Posts
    345
    1. you need a return value for InitialiseX, in both .h and .cpp files, and you need to add include guards for the .h file, to make sure that it doesn't get included more than once in the same .cpp file:
    Code:
    //in TheClass.h
    #ifndef _THECLASS_H_
    #define _THECLASS_H_
    
    Class MyClass {
    public:
    	void InitialiseX(int Number);
    private:
    	int x;
    };
    
    #endif
    2.because x is declared as private, you can only access x in MyClass member functions, to access x everywhere, declare it as public.

    3.I suggest you stick with this way, it's better to have declarations in one file, and implementation in another.

  6. #6
    Epo
    Epo is offline
    Registered User
    Join Date
    Jun 2003
    Posts
    361
    Thanks for the help guys It's helped out probably more than you think

    Shakti: Is there a trick to indenting? Cause each time I press the "Tab" button the focus jumps out of the text box window and onto the Submit Reply button.

    One last question. I'm looking to stay pretty organized. Here's how my program sort of works:

    I have functions for my window (in the class Window):
    GetWindowSize() and InitialiseWindow()

    Then, I have functions for drawing to my window (in the class Render):
    InitDrawingSettings() and DrawToWindow()

    There are also Functions that receive input (in the class Input):
    GetKeyboard() and GetMouse()


    Is there a way to set these up, so that I could do something like:
    Window.Input.GetMouse()
    or
    Window.Render.InitDrawSettings()

    and if so, would I declare all of these classes in the same .h file (or seperate .h files for each)?

    Thanks for the help so far

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,505
    > Shakti: Is there a trick to indenting?
    Yeah, you write the code you want to post in your text editor you use for writing code.

    > and if so, would I declare all of these classes in the same .h file (or seperate .h files for each)?
    The usual rule is each class has its own .h

    > Is there a way to set these up, so that I could do something like:
    Here's the basic idea
    Code:
    class Window {
        Render  Render;
        Input   Input;
    };
    You need to choose whatever names you want, and decide on how much visibility to give the outside world.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  8. #8
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Keep 'em in separate headers. That way, if you change one, you need not recompile the entire thing.

    Before you call any non-static member functions of a class, you must first create an instance of the class. Then you can call the functions for that instance of the class:
    Code:
    class A {
      void f( );
    };
    
    int main( )
    {
      A obj1;
      // ... or ...
      A* obj2 = new A;
    
      obj1.f( );
      obj2->f( );
    
      // And of course, clean up memory from new
      delete obj2;
    }
    Instances of one class can be member data of another class as well.
    Code:
    // A.h
    class B; // Forward declaration... Definition of B not needed yet.
    
    class A
    {
    public:
      A(B&);
      void f( );
    private:
      B& data;
    };
    
    // A.cpp
    #include "B.h"
    
    A::A(B& src)
      : data(src)
    {
    }
    
    void A::f( )
    {
      data.do_something( );
    }
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  9. #9
    Epo
    Epo is offline
    Registered User
    Join Date
    Jun 2003
    Posts
    361
    Awesome So far so good.

    I've been looking through some tutorials and have come across this code:

    Code:
    #if !defined(AFX_CUBOID_H__AE25AF5F_AE56_48F5_99DC_47CAAA14F245__INCLUDED_)
    #define AFX_CUBOID_H__AE25AF5F_AE56_48F5_99DC_47CAAA14F245__INCLUDED_
    
    #if _MSC_VER > 1000
    #pragma once
    #endif // _MSC_VER > 1000
    It comes from a Cuboid.h file and is for a CCuboid class. I was wondering if anyone could explain what those lines do. I've seen them quite often, but never are they explained.

    Thank you for the help so far

  10. #10
    Epo
    Epo is offline
    Registered User
    Join Date
    Jun 2003
    Posts
    361
    I'm currently on my fifth attempt on classes, and this one's looking more hopeful than any other one I've tried so far

    Here's my bind...Constructors:

    I read that I can make more than one constructor:
    This is in my Game.h file:
    Code:
    class Game
    {
    public:
    	Game(void);
    	Game(HINSTANCE *hInstance);
    	~Game(void);
    private:
    	HINSTANCE MainInstance;
    }
    My Game.cpp file consists of:
    Code:
    #include "Game.h"
    #using <mscorlib.dll>
    
    Game::Game();
    {
    //This one's empty because I never want to use it
    }
    
    Game::Game(HINSTANCE *hInstance)
    {
    	MainInstance = hInstance;
    	Fullscreen = GetScreenMode();
    	InitWindow();
    }
    
    Game::~Game(void)
    {
    //Haven't gotten here yet
    }
    And finally, my Main Coding CPP (Main.cpp) consists of this:
    Code:
    #include "Game.h"
    int APIENTRY WinMain(HINSTANCE MyInstance, HINSTANCE PrevInstance, LPSTR kposzArgs, int nWinMode)
    {
    	MSG Msg;
    	Game(&MyInstance) MyGame;
    	
    //Ignore the part beneath here, I'm concerned about the above
    	while(GetMessage(&Msg, NULL, 0, 0))
    	{
    		TranslateMessage(&Msg);
    		DispatchMessage(&Msg);
    	}
    	return Msg.wParam;
    }
    Now, you may be looking at this and thinking "What in the world is he trying to do?" Which is okay. Because I get a few errors when I try to compile

    So, the questions:
    1) (Main.cpp)How do I specify which Constructor to use when I declare the MyGame variable?

    Hmm...I guess that's it I have many errors, but I think figuring this one out will be able to solve a good portion of them. So for now, yeah I appreciate any help.

  11. #11
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Well, your missing a semi-colon after your class declaration.

    The constructor to be used is determined by what parameters you pass the object when you create it. So, your instantiation should look like this:
    Code:
    Game MyGame(&MyInstance); // Passed an HINSTANCE*, so thats the constructor it uses.
    
    // Alternatively
    Game MyGame2; // Calls the default constructor since you passed no parameters.
    // Equivalently...
    Game MyGame3( ); // Again, default constructor.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  12. #12
    Epo
    Epo is offline
    Registered User
    Join Date
    Jun 2003
    Posts
    361
    Thank you for the help with that Zach I'm down to one error left. It's more of a Windows API question than Classes (I think) though so I'm gonna post it in the Windows Section of the forum. If anyone here knows a tad about "Skeleton Windows" please have a look at it (It will be up shortly. Or it will be up now. Depending on how long after I post this you read this)

    Thanks again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 09:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM

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