OpenGLmaster1992
OpenGLmaster1992

Reputation: 281

C++ How to access an object of another class?

I want to have 1 class that holds all objects to my other classes. So for example: If player class want a member of enemy class, I want to access the enemy class using that 1 class.

An example:

class objectHolder{
public:
    enemyClass enemy;
};

class enemyClass{
public:
    void member();
};

class player{
public:
    objectHolder oh;
    oh.enemy.member(); //I KNOW THIS IS ILLEGAL BUT I NEED SOMETHING LIKE THIS
};

I know the code is incorrect and does not compile well, but I hope you get the idea. Does anyone know how to actually do this? Because I actually need 1 class that all classes can access. Every class can call getters and setters and stuff from other classes by using that 1 big class.

I hope I was clear enough, thanks in advance.

Upvotes: 0

Views: 13583

Answers (3)

0xFFFFFF
0xFFFFFF

Reputation: 333

You can not call function in class body ... try this code may useful

 class enemyClass{
 public:
void member(){std::cout<<"Test";}
 };
class objectHolder{ 
public:
enemyClass enemy;
enemyClass getEnemy(){return enemy;}
};

class player{
public:
objectHolder oh;
void getresult(){oh.getob().member();}
};
 int main()
{
player p;
 p.getresult();
 }

Upvotes: 4

Paul Evans
Paul Evans

Reputation: 27567

oh.enemy.member(); is a perfectly legal C++ statement since all members involved have public access. Where you've put it makes no sense however since statements can only appear in a function body.

Upvotes: 2

LeChiffre
LeChiffre

Reputation: 596

1) Make a singleton

2) Initialize it & include all objects you want to hold.

3) Access the singleton instance from anywhere you please.

4) Realize that this is a horrible way to structure your program.

Upvotes: 1

Related Questions