Help with header file

Started by
4 comments, last by pragma Fury 18 years, 10 months ago
I am trying to allow this phrase to access name which is private in a class located in a header file. char move; int currentroom = 0; cout << "You emerge in the " <<roomsArray[currentroom].name; [code\]
Computers are worlds of Exploration?
Advertisement
You have to grant access to it somehow. Either by making it public, creating some method to retrieve it (i.e. a "getter" function) or declaring the code accessing it as a friend.
There are other ways around it too if you for some reason can't change the file, but they are only last resort hacks.
Do you have control over the header file? Just make it public (or put in a public get function, modular code is important however it does not appear you would gain anything from a get function in this case)

**edit** [lol] today is just not my lucky day! Yep nothing new here that is not said in above post...
Yeah I am programming the game its just I only want name as private so it can only be accessed by certain calls
Computers are worlds of Exploration?
Quote:Original post by C_Programmer0101
Yeah I am programming the game its just I only want name as private so it can only be accessed by certain calls
Here's a few variants you might use.
// direct accessclass foo {public: int bar;};// read-only accessclass foo {public: const int bar; foo(int _bar) : bar(_bar) {}};// "getter" functionclass foo { int bar;public: int get_bar() const { return bar; }};// friend functionclass foo { friend void func(foo f); int bar;};void func(foo f) { f.bar = 3;}

But maybe a "Print" function might be a better idea of you want to keep the name internal.
Ways that work, but should NEVER be used.

  1. #define private public
    # include "TheHeader.h"
    #undef private
    // everything that was private in "TheHeader.h" is now public..

  2. Or you could do some scary casting...
    // TheHeader.hclass PrivateMembers {  int a;  int b;};// SomeOtherFile// must mirror PrivateMembers!class PublicMembers {public:  int a;  int b;};...PrivateMembers priv;PublicMembers *p = reinterpret_cast<PublicMembers*>(&priv);p->b; // no problem!

  3. Or even worse:
    class PrivateMembers {  int a;  int b;};...PrivateMembers priv;int &ref_b = *(reinterpret_cast<int*>(reinterpret_cast<char*>(&priv)+sizeof(int)));ref_b = 5; // now priv.b == 5


This topic is closed to new replies.

Advertisement