-
Inheritance
Code:
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.
-
You need a setter (ie make a function SetA). And make main return int.
-
Elysia, can you help me more?
Coz I typed k.a not k.a() so we can't call it.
-
The root issue is that you need to create a setter function. There isn't one. That's your job.
-
That's easy for me. I had created more and more like those functions GetA, SetA... They didn't work.
Code:
int& x::GetA(){return a;}
void x::SetA(){cout<<"Enter the value of a: "; cin>>a; }
OR void x::SetA(int value){ a=value; }
-
The first setter is wrong. A setter accepts a value to set and returns nothing.
Otherwise they're valid. Put them in your class and call them.
-
We can't use those functions in main() so how can we call them?
-
Of course you can. Post your current attempt so we can see what's wrong.
-
We are not allowed to use those functions in main().
-
Then you're screwed.
Unless you can change the access to the member data, you must change the code in main.
-
The problem you are experiencing is that x::a is private, which means nothing in y can access it due to public inheritance. Either you make a protected and create public setter and getter in y or you create public setter and getter in x.
-
There is an answer coz it's an exam question. I made the code smaller for you.
Somebody told me about friend functions. What about friend functions?
-
Post entire code, you may have missed something you deemend irrelevant but that is actually very relevant to the issue.
-
If you are interested in, I can post the whole code. It's really long.
-
Its the only way for us to help you I think since Elysia and I presented you with the obvious solutions to the problem.