vishal
vishal

Reputation: 77

how compiler differentiates between private and public data in C++?

For example,

Class Test {
        private:
            int x;
        public:
            int y;
}obj;

Now, obj.y can be accessed but not obj.x

My question is how compiler restricts access to private data?

Besides, how can I implement access specifiers in C structures?

Upvotes: 1

Views: 1508

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171413

My question is how compiler restricts access to private data?

When the source code refers to any variable a C++ compiler has to do name lookup to find the variable (it could be a local variable, a member variable, a global variable etc.) and it has to do access checking. The compiler has all the information about the types, variables and scopes, so when the source code refers to a variable the compiler knows if the variable is accessible. If the variable isn't accessible the compiler rejects the source code.

Asking "how" doesn't really have an sensible answer - it's the compiler, that's what it does. Knowing how it does it is no help to you if you're trying to write C code to do the same, because what you can do in a program's source code is entirely different to what a compiler does. It's like asking how an aeroplane flies, then asking how you can fly in a car. Knowing the answer to one is irrelevant to the other.

Besides, how can I implement access specifiers in C structures?

Two options:

  1. C doesn't support that, use C++

  2. store a void* in the struct which points to some opaque type, and only have "private" functions (i.e. internals to the API) know the details of that opaque type.

Here's a quick example

//
// in header only "public" data is visible
//

struct Data {
    int some_number;
    void* private_data;
};

Data* create_Data(int i, int j);
void manipulate_Data(Data*);

//
// in source file, these functions know what the `void*` points to and can use it
//

struct InternalData {
    int another_number;
};

InternalData* get_internals(Data* d)
{
    return (InternalData*)d->private_data;
}

Data* create_Data(int i, int j)
{
    Data* data = (Data*)malloc(sizeof(Data));
    data->some_number = i;
    InternalData* internal = (InternalData*)malloc(sizeof(InternalData));
    internal->another_number = j;
    data->private_data = internal;
}

void manipulate_Data(Data* d)
{
    data->some_number += get_internals(d)->another_number;
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409442

The compiler have all information about all the code in a translation unit (a source file and all included header files), and can therefore keep track of which members are private and which are not. How the compiler does it is not relevant, and different compilers can implement it differently.

Private/public members is a pure compile-time concept, and there is nothing in the compiled executable code that enforces it.

Upvotes: 9

Related Questions