Inheritance + access mode

Hello every one,

Pls tell me what is wrong with following code?
I am not able to recognize.


class A{
protected:
int i;

};

class B: public A{


public:
void set(A a,int y){
a.i=y;

}

};


Thanks in advance.
Actually, I had this very same problem just today. A derived class can access the base's protected and public members, but only of the current instance, not of other instances.
1
2
3
this->i=0; //OK. Accessing though 'this'.
i=0; //OK. Note implicit use of 'this'.
a.i=0; //Wrong! 
Why? To be honest, I don't know.

Is that your complete implementation or just a simplification? There's one or two ways you could implement the same functionality. And also that code doesn't work, even if it did somehow compile.
hello ShubhadaJS,

private
Class members declared as private can be used only by member functions and friends (classes or functions) of the class.

protected
Class members declared as protected can be used by member functions and friends (classes or functions) of the class. Additionally, they can be used by classes derived from the class.

public
Class members declared as public can be used by any function.


the definition of 'protected' just doesn't let you access a member of an extenal object. a is a parameter and hence external.

Plus void set(A a,int y) will most likely not do what you expect (it won't change the object outside 'set')
Topic archived. No new replies allowed.