0

Am new to cpp. Generally, friend function could access private and protected members of the class but when I tried to use friend function in derived class am observing weired behavior..

class first
{
  int a;
};

class second : public first
{
  public:
   friend void hai ( second );
};

void hai ( second s )
{
 printf("%d",s.a); // It says compilation error 
}

void main()
{
  second s;
  hai(s);
}

If I make a to public, it works fine.

Could somebody clear me, why shouldn't I access a if its in base private scope.

Regards Prasath S.

  • int a; is not part of second class and has not inherited due to default private access specifier – Sumeet Dec 13 '16 at 10:28

4 Answers4

0

Make field a protected, not private.

Private fields can be accessed only from class declaring them.

Nikolay
  • 1,949
  • 18
  • 26
0

Your error is here:

class first
{
  int a;
};

The default for class members is private so you won't have access to it from derived classes.

Private members are only accessible from the same class. The line

class second : public first

doesn't change the private member to public, so you have the choice between making a protected/public or you include a public/protected get/set function to first, which will manage the access to a.

izlin
  • 2,129
  • 24
  • 30
0

why shouldn't I access a if its in base private scope.

friend function can access private members of the class that it friends to.

However in this case, member a in base class is private by default and therefore not inherited to child class.

Public inheritance requires protected or members of base class to be inherited by child classes. So for your example to work, you can use protected member a

class first
{
    protected:
        int a;
};
artm
  • 17,291
  • 6
  • 38
  • 54
0

first::a is private in class first

class second is derived publicly from class first, so:

  • all the public members of class first are public in class second and can be accessed via objects of class second.
  • all the protected members of class first are protected in class second and cannot be accessed via objects of class second.
  • all the private members of class first are inaccessible in class second and cannot be accessed via objects of class second.

Therefore, you cannot access first::a via object of class second.

For more information: Can a friend class object access base class private members on a derived class object?

Why can a derived class not access a protected member of its base class through a pointer to base?

Community
  • 1
  • 1
sameerkn
  • 2,209
  • 1
  • 12
  • 13