hey,thats my first post,i started recently to have for hobby programming,and i am really interesting to learn.
anyway i have a problem i write a program that use some classes objects my problem is probably fundamental but i couldnt find answer on net.

i have one header file that i have class declaration public private etc

example:

header.h

class alpha{
public:
void test();
private:
int x;
};

i have one cpp file that includes that header and has the methods.

#include "header.h"

void alpha::test()
{
something
}

now in my program i want to declare objects in a header so multiple cpp files can read and write and in general work.

program.h
 alpha beta();

and cpp1

beta.test();

cpp2

beta.test() change it

sorry for bad form of the post but as i said my first :D

the code is wrong but i wanted you to understand the idea
i used static but when i run it,is like they dont work

Nick Evan commented: good 1st post. +16

Have you tried doing this in one file? Maybe that will help you understand what's going on. You can't declare an object in one file (or a method for that matter) and then expect to be able to use/change it somewhere else. Your objects are not globally accessible (unless declared as such).

Have a look at how the call stack works - it's a challenging topic if you're new to programming, but will help you tremendously I think.

I don't see a main() function in any of your posted code. Do you have a proper main() in one of your *.cpp files?

An example:

//sample.h
#ifndef SAMPLE_H    //check for previous inclusion
#define SAMPLE_H    //establish header guard

class Sample {
 private:
   int myInt;

 public:
   void SetInt(int);
};                  //end class definition, notice the ';'

#endif              //close SAMPLE_H header guard
//sample.cpp
#include "sample.h"

//define Sample::setInt()
void Sample::SetInt(int newInt) {
  myInt = newInt;
}  //end Sample::SetInt()
//main.cpp

#include "sample.h"

int main() {
  const int SAMPLE_VALUE = 5;
  Sample mySample;

  mySample.SetInt(SAMPLE_VALUE);

  return 0;
}

You have to make sure that all 3 files are properly coordinated. Also, you need to make sure that your implementation *.cpp file is part of your build. It needs to either be listed in your make file or part of your project in your IDE.

yes it has main function,was examples what i posted.

to be more honest i am beginner and in that site i saw exercises that beginners can try to make for improving their selves.

and i saw the one that suggest to make text based rpg.
its almost done just its way too chaotic cause most of the functions take place in one cpp(not the one that i have the main() function)

and my intention was to keep another header file with functions prototypes and the objects that i want and in some various cpp files to separate the functions and use of methods so will be more readable.

but i think i will give it up for now,and continue my book and catch it up later.

I think this site will help you a lot. Don't give up!

I guess I'm having a hard time understanding what you're trying to accomplish. Are you trying to break one (1) single *.cpp file into 3 separate files: a header (*.h), an implementation (*.cpp), and a main (*.cpp)? Or are you trying to do something else?

I guess I'm having a hard time understanding what you're trying to accomplish. Are you trying to break one (1) single *.cpp file into 3 separate files: a header (*.h), an implementation (*.cpp), and a main (*.cpp)? Or are you trying to do something else?

i dont know how to explain it well.
my problem is only with the class onbjects.
forget please main() everything is ok with that.
what i want to do is one (*.cpp) file that has

classobject alpha;
alpha.methodhi();
beta.methodhey();

i want to move the part

classobject alpha;

to a header file and leave

alpha,methodhi()

to 1.cpp and

beta.methodhey();

to 2.cpp.

i think thats more or less what i want to do,cause when i do it i recieve error.
i used

static classobject alpha;

compiles ok,but when i go to change some values its like they dont change.

You have a project. Its all in one file. What you do is divide it into tasksize parts, eg ReadInput.cpp, WriteScreen.cpp, Treasury.cpp and create the header files with the same name but with the .h extension, in the header files you put the class definitions. In the cpp files you put the methods (constructors where you can create the objects, functions that you will need etc) and include the neccessary header files for each. In the main function you try make it so when the next programmer reads your code he will check header files and be able to write some other task without looking how you did the methods. Then your ace :)

forget please main() everything is ok with that.

There's the problem. Based on the syntax of the code you indicate you're trying to move, I'm not so sure everything is okay with it. You don't seem to want to touch it, but you'll eventually have to.

What are 1.cpp and 2.cpp used for? Is 1.cpp where your main() is and 2.cpp where you want this other code?

i want to move the part

classobject alpha;

to a header file...

Are you trying to make the "classobject" object identified as "alpha" a global object? It's not really advisable to make a non-constant object global, but there is no problem doing this. I really can't see any other reason you would want to move this declaration to a header... If you don't want it to be global, this declaration MUST be inside of a function, such as main()...

alpha.methodhi();
beta.methodhey();

These are calls to member methods. You can't randomly move them to another *.cpp file without putting them inside some sort of executable block of code, such as another function that you call from main().

Now do you see why I'm so hung up on your main()? There must be some sort of logical path of executable code that can be followed from main() to the code you are trying to move to different files. Without that logical path of executable code, whatever you move will not be accessible, will not execute, and could potentially cause compilation errors.

I think I understand what you want to do, so let me put up a more consistent code and you tell me if that is what your question was about:

In Foo.h:

class Foo {
  private:
    int value;
  public:
    void PrintValue();
    void SetValue(int aValue);
};

In FooPrint.cpp:

#include "Foo.h"
#include <iostream>

void Foo::PrintValue() {
  std::cout << "Value is: " << value << std::endl;
};

In FooSet.cpp:

#include "Foo.h"

void Foo::SetValue(int aValue) {
  value = aValue;
};

And, finally, in main.cpp:

#include "Foo.h"

int main() {
  Foo f;
  f.SetValue(42);
  f.PrintValue();
  return 0;
};

The above scheme can be done (but is rather unusual) if the class (e.g. Foo) is very large (the implementation in a single cpp would be very large) or if there are some methods for which you would like to have a few alternative cpp files (e.g. FooPrintVersion1.cpp and FooPrintVersion2.cpp). This is totally fine (still unusual though) but OK.

If you want to compile this, assuming you are using gcc (or MinGW), you would have to do this command-line compilation:

g++ main.cpp FooPrint.cpp FooSet.cpp -Wall -o MyFooProgram

Or, if you have two versions of FooPrint, then you would have to different compilation commands, like so;

g++ main.cpp FooPrintVersion1.cpp FooSet.cpp -Wall -o MyFooProgramV1
g++ main.cpp FooPrintVersion2.cpp FooSet.cpp -Wall -o MyFooProgramV2

If you are using Visual Studio or another IDE of the sort, you would have to add all the cpp files that you have to the build (i.e. "Add source file to project/solution" somewhere in the menu).

I hope this was the question you were asking (it seemed so from the original post at least). Otherwise, please provide a piece of code that is at least valid C++ syntax (because function calls in the middle of nowhere is not valid C++ syntax).

i am bad lol,all this thread and i cant explain what i want.ok last try then i will continue with my deitel book and catch it up later.

i will try to implement my code from what i fix,(text based rpg)
consider that everything is working fine.i will try to post parts cause all is too big and chaotic :D i will make 2 parts,1 that i have now and works and one what i want to accomplish and it doesnt.

part 1 works!
main.cpp

#include <cmath>
#include "Game Fuctions.h"
using namespace std;

int main()
{
    srand(time(0));
    intro();
}

playerclass.h

#include <string>
using namespace std;

class Player
{

public:
    void setHitPoints(int);
    int getManaPoints(int);
private:
    int HitPoints;
};

playerclass.cpp

#include "PlayerClass.h"
#include <cmath>
void Player::setHitPoints(int HP)
{
    HitPoints=HP;
}
int Player::getHitPoints()
{
    return HitPoints;
}

now gamefuctions.h

#include "PlayerClass.h"
using namespace std;

void hPlayer(int);

gamefuctions.cpp

#include <iostream>
#include <iomanip>
#include "Game Fuctions.h"

//PlayerList
//Class,Health,Mana,Gold,Armor,BaseAttack,RangeOfAttack
 Player warrior("Warrior",150,10,0,1,20,5);
 Player playerClass("",0,0,0,0,0,0);
void hPlayer(int PlayerC)
{
    switch (PlayerC)
    {
        case 1:
            playerClass.setHitPoints(warrior.getHitPoints());
            break;
    }
}

that works,i remind the code is cutted cause is big and show only what i need.

part 2,what i want to do

now gamefuctions.h

#include "PlayerClass.h"
using namespace std;

//PlayerList
//Class,Health,Mana,Gold,Armor,BaseAttack,RangeOfAttack
 Player warrior("Warrior",150,10,0,1,20,5);
 Player playerClass("",0,0,0,0,0,0);

void hPlayer(int);

gamefuctions.cpp

#include <iostream>
#include <iomanip>
#include "Game Fuctions.h"

void hPlayer(int PlayerC)
{
    switch (PlayerC)
    {
        case 1:
            playerClass.setHitPoints(warrior.getHitPoints());
            break;
    }
}

and i got the error :

build/Release/Cygwin-Windows/main.o:main.cpp:(.bss+0x0): multiple definition of `_playerClass'
build/Release/Cygwin-Windows/GameFuctionsDef.o:GameFuctionsDef.cpp:(.bss+0x2c0): first defined here

if i use static compiles but its like is not arranging the value.

gamefuctions.h

#include "PlayerClass.h"
using namespace std;

//PlayerList
//Class,Health,Mana,Gold,Armor,BaseAttack,RangeOfAttack
 static Player warrior("Warrior",150,10,0,1,20,5);
 static Player playerClass("",0,0,0,0,0,0);

void hPlayer(int);

i want that cause gamefuctions.cpp is really big,so i would like to split it in seperate cpps to be smaller! and more clean.
thats the best i can do,thanks for your help anyway :D

The code you have posted looks correct.

The error you cite is the result of "PlayerClass.h" being included into your main.cpp file multiple times through your other headers and implementation files. You need to add include guards to your headers to prevent multi-inclusion errors.

#ifndef SAMPLE_H      //check for existence of #include guard
#define SAMPLE_H      //establish #include guard

#include <string>
using namespace std;

class Sample
{

public:
  //...
private:
  //...
};

#endif  //SAMPLE_H   //end #include guard

Another problem you will have is that each compilation of those separate cpp files will have its own instances of "playerClass" and "warrior". This most probably not desirable. You could fix this with use of the "extern" keyword in front of those two global variable declaration, but I cannot, for the life of me, recommend that.

I highly suggest you make all your game functions as part of a game class (that handles the game):
gamefunctions.h:

#include "PlayerClass.h"
//using namespace std; //do not import namespaces in a header file!!


class Game {
  private:
    //PlayerList
    //Class,Health,Mana,Gold,Armor,BaseAttack,RangeOfAttack
    Player warrior;
    Player playerClass;

  public:
    Game() : warrior("Warrior",150,10,0,1,20,5), playerClass("",0,0,0,0,0,0) { }; 
  
    void hPlayer(int);
    //all your other functions ...
};

Then in gamefunctions.cpp (or in a few separate cpp files):

#include <iostream>
#include <iomanip>
#include "gamefunctions.h"

void Game::hPlayer(int PlayerC) // now a member function.
{ 
    //And the rest of the code remains essentially unchanged.
    switch (PlayerC) 
    {
        case 1:
            playerClass.setHitPoints(warrior.getHitPoints());
            break;
    }
}

And finally in main.cpp:

#include <cmath>
#include "gamefunctions.h"
using namespace std;

int main()
{
    srand(time(0));
    Game my_game;    //create an instance of the game!
    my_game.intro(); //and run it!
}

That ought to be much better than relying on global data. BTW, you can very often replace global data with an enclosing "super" class. With this, you will be one step closer to breaking the C-programming habits and becoming a C++ programmer!

thanks a lot that what i was looking for :) problem solved :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.