class x{int a;};
class y:public x{};
main(){y k;  k.a=3; }

How can I access "k.a"?
PS: You can't change or omit any part of the code.
a have to be private.
Member access specifier have to be public ( class y::public x ).
You can add functions to x class but you can't add data members to x class.
You can add functions to y class too.
-> Maybe we need to type a friend function.

Just add a public function to x returning the value, you already have the answer staring at you in the directions.

Just do it and then see what happens. Lemme say it-> x::a is not accessible.
Btw we can't change main().

That's because members of a class default to private if you don't give the access specifier. You have to access it through the public functions, as I mentioned.

Edited 5 Years Ago by MosaicFuneral: n/a

That's because members of a class default to private if you don't give the access specifier. You have to access it through the public functions, as I mentioned.

I know, we need to access it in main() as "k.a" not "k.a()"?

Btw we can't change main().

Unless you change main, you do not have a well-formed C++ program - main must return an int

class x { int a ; protected: int& cheat() { return a ; } } ;

class y : public x { public: y() : a( cheat() ) {} int& a ; } ;

int main() { y k ; k.a = 3 ; }

Unless you change main, you do not have a well-formed C++ program - main must return an int

class x { int a ; protected: int& cheat() { return a ; } } ;

class y : public x { public: y() : a( cheat() ) {} int& a ; } ;

int main() { y k ; k.a = 3 ; }

Your answer is the only original one of a lot of responses to this question.
Will "k.a" be accessible by that way?

Edited 5 Years Ago by freakyboard: n/a

Your answer is the only original one of a lot of responses to this question.
Will "k.a" be accessible by that way?

Yes, it will...

Technically speaking you can change the publicity of a in the derived class by doing this:

class x
{
   int a;
};

class y : public x
{
public:
   x::a;
};

That said, this is very likely not what you should be doing at all. Regardless of what you think you're supposed to do, MosiacFuneral is right, the best solution by far is to use public functions to get k. While vijayan121's code works, as he himself said, it's a bit of a cheat, and when it comes to real applications, the best way to do it is with public functions.

Technically speaking you can change the publicity of a in the derived class by doing this:

class x
{
   int a;
};

class y : public x
{
public:
   x::a;
};

No.

Oh, hey, whoops. vijayan121 is right, what I said was wrong. Sorry, I was really sleepy when I wrote that. You can change the access of members from the base class, you can only do that to things the derived class would be able to see normally, so you couldn't make a private member in the base class non-private. Sorry about that, didn't intend to misinform.

This article has been dead for over six months. Start a new discussion instead.