class A {
public:
protected:
  int i;
};


class B : public A {
  friend void f(A*, B*);
  void g(A*);
};

void f(A* pa, B* pb) {
//  pa->i = 1;
  pb->i = 2;

//  int A::* point_i = &A::i;
  int A::* point_i2 = &B::i;
}

void B::g(A* pa) {
//  pa->i = 1;
  i = 2;

//  int A::* point_i = &A::i;
  int A::* point_i2 = &B::i;
}

void h(A* pa, B* pb) {
//  pa->i = 1;
//  pb->i = 2;
}

int main() { }



class A {
public:
protected:
  int i;
};


class B : public A {
  friend void f(A*, B*);
  void g(A*);
};

void f(A* pa, B* pb) {
//  pa->i = 1;
  pb->i = 2;

//  int A::* point_i = &A::i;
  int A::* point_i2 = &B::i;
}

void B::g(A* pa) {
//  pa->i = 1;
  i = 2;

//  int A::* point_i = &A::i;
  int A::* point_i2 = &B::i;
}

void h(A* pa, B* pb) {
//  pa->i = 1;
//  pb->i = 2;
}

int main() { }

why line 25 is a error here ? please explain in detail. thanks. firstly, explain me line 25.i am learning inheritance. thanks.

The compiler explains it pretty well:

error: 'i' is a protected member of 'A'

That's pretty much all there is to it. The member function g is a member of class B, and the function f is a friend of class B. They both can only have access to private / protected members of class B, not those of class A. Before you say "what a minute, the protected members of A are accessible from B", I will correct you on that and state it more precisely: "member functions or friends of B have acces to protected members of A that the objects of class B have inherited".

This boils down to a case of "all B's are A's but not all A's are B's". In other words, the access to the members of A is granted to members / friends of B on the condition that they come from an instance of B. That's why you can't get access to them directly, either by pa->i or &A::i, you must always go through B class first.

commented: excellent!! excellent!! +3
Member Avatar for iamthwee

That's such a terrible example for an introduction into OOP. Consider revising your learning resources.

iamthwee then can you give me some link ?

Member Avatar for iamthwee

In general if you google it, google will rank the most useful near the top. I really despise such abstract examples with classes called A and B, having a friend functions. Then expecting newbies to predict the output.

There are lots of real world examples/tutorials to work from which explains OOP concepts in better and more intuitive ways.

int A::* point_i = &A::i;

what does this statement is trying to do ? please elborate. what is *point_i is here ? and what all is this statement means ? thanks.

Look up "pointer to member".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.