-5

Can we use public data member or member function in function which is declared in program but that are not member of that class ?

Parth
  • 11
  • 1
  • 3

3 Answers3

0

If the non-member function in question has an object on which to invoke the member functions, then yes - that's the idea with public members. For example:

class X
{
  public:
    void f() { }
    int n_;
};

int main()
{
    X x; // an actual object/variable of type X
    x.f(); // can access public members
    x.n_ = 3;
}
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • There is a rule in c++ which is ["Never specify public or protected member data in a class."](https://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap7.html) – goGud May 01 '15 at 11:35
  • 1
    @goGud: That's not a "rule in C++", just someone's excessively restrictive style guide. – Mike Seymour May 01 '15 at 11:44
  • @goGud: that's a reasonable guideline for people to read, though calling it a "rule" makes it sound Standard-mandated... it is of course up to the programmer. Cheers. – Tony Delroy May 01 '15 at 11:46
0

this is possible by using friend function concept. any function that is not member function of that class then we can declare this function with friend keyword as friend function. now by using this friend function we can access all private, protected, public data members with the help of object of that class.

Prashant Mishra
  • 167
  • 1
  • 9
0

Public data members of a class can be accessed by any function.

Public member functions of a class can be called by any function.

That is sort of the purpose of making class members public.

Naturally, there are other conditions (e.g. a function that calls a non-static public member function generally requires access to an instance of the class i.e. an object). Such conditions, if not met, will typically prevent code compiling or result in undefined behaviour - but that is unrelated to the question of whether a member is public or not.

Peter
  • 35,646
  • 4
  • 32
  • 74