How do I use a .h file for a class?

I wrote a simple date class and could not get it to work until I put all the code in main(). Then it worked like a charm. I have not been able to create a separate .cpp file and get it to work with my existing main().
I tried to follow http://www.cplusplus.com/forum/articles/10627/ which is a closed article, with no success. I tried every combination I could think of and was unable to compile without error. (Linux Mint 17,code::blocks 13.12, G++ 4.8.2). I did finally get it to work by putting *all* my code in the .h file and #including the .h file (and nothing else) in the .cpp file. This is not how it's supposed to work. I'm getting old and can not afford to pull out any more hair. Ideas?

This is unbelievable! I just tried this on another computer, same OS same version of Code::Blocks and G++.
And it bloody works! I'm tired and going to bed now but I will delve deeper into this tomorrow. This has been very frustrating but I'm nearing the end. Thanks to those who offered to help.
Last edited on
Can you tell us what errors you were getting or problems you were having when you tried to implement the project as described by the article?
header:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//myClass.h
#ifndef MY_CLASS_H
#define MY_CLASS_H


class myClass
{
     //input variables and functions here
    //example function
public:
     int m_variable;
     void changeVariable();
};

#endif 


implementation:
1
2
3
4
5
6
7
8
9
10
//myClass.cpp

#include "myClass.h"

void myClass::changeVariable()
{
     m_variable = m_variable * 2;
     return;
}
//that would be it for the .cpp file 


now for main
1
2
3
4
5
6
7
8
9
#include "myClass.h"

int main()
{
     myClass Object; //default constructor used
     Object.m_variable = 2;
     Object.changeVariable(); // the value of  Object's m_variable will now be 4
     return 0;
}


First, make sure that all the files (main.cpp, myClass.h, and myClass.cpp) are all in the same folder. The #ifndef is important.
Also, make sure that #include "myClass.h" is at the top of both main.cpp and myClass.cpp. Classes that you define on your own have the name in parenthesis, standard libraries have the name is angle brackets (< and >).

What errors was your compiler giving you when you tried to compile?
Topic archived. No new replies allowed.