Sign in to follow this  
C_Programmer0101

Help with header file

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites
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 access
class foo {
public:
int bar;
};

// read-only access
class foo {
public:
const int bar;
foo(int _bar) : bar(_bar) {}
};

// "getter" function
class foo {
int bar;
public:
int get_bar() const { return bar; }
};

// friend function
class 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.

Share this post


Link to post
Share on other sites
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.h
    class 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



Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this