curious about what private will do exactly!!

hello,

class Test
{
private:
int pri;

public:
int pub;
...
}

main()
{
Test test1;
set all variables

cout<<"public: "<<test1.pub<<endl; //can be accessed
cout<<"private: "<<test1.pri<<endl;//not possible
}

just curious to know what exactly private ll do such that we wont be able to access private variables.
i mean is it going to set any particular flags for private variables so that direct access is denied.
Private does nothing. It is merely a hint/comment for the compiler so it signals any attempts to directly access those members as errors, but it does not have any influence on the generated program code (contrary to e.g. Java or C#). You can easily access private variables by e.g. hand-crafted pointer and nothing is going to stop you.
> just curious to know what exactly private ll do such that we wont be able to access private variables.
> i mean is it going to set any particular flags for private variables so that direct access is denied.

Access control is enforced at compile time, not at run-time. When a member is accessed, the compiler checks the access specifier for it. In C++, there is no run-time overhead for access checks.

The is another implication:
In your class Test, if both non-static members were public, it would be a standard-layout type - it has the same object representation as the equivalent C struct. It can be used interoperably with code written in other programming languages.

On the other hand, if one is public, and the other is private, Test is not a standard-layout type and and object of the type can't be (portably) passed to a C function.
can static variable be intialized directly even if it is in private.

class Statik
{
private:
...
static int pri;
public:
...
};

int Statik::pri=10; //pri gets intialized to 10 even pri comes under private
^ Yes.
It is the same as implementing private member functions.
Topic archived. No new replies allowed.