0

This is a sample code explaining the question.

Why does the "display()" not call the member function rather it calls the non member function ?

    #include<iostream>
    using namespace std;

    class foo
    {
        private:
            int num;

        public:

            // Constructor
            foo() : num(0){}

            // Member function
            void display()
            {
                cout<<"This function is inside class foo"<<endl;
            }
    };

    // Non-member function
    void display()
    {
        cout<<"Non-member function called."<<endl;
    }

    int main()
    {
        foo obj;

        obj.display();      
        display();          // Why does this not call the class member function, 
                            // even though it is public ?

        return 0;
    }

Kinda new with the language.

  • 3
    non-static member functions need to be called on an instance of a class. ie `object.memberfun();` If there were lots of classes with a `display` function which should be called? If there lots of objects of type `foo` which `display` should be called. This is covered in any good book in C++ [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Richard Critten Aug 27 '22 at 21:34
  • 1
    Member functions are called either directly by, or through (as in the case of `obj.display()` an object. If there is no object to call through, any defined free function implementation is called. – jkb Aug 27 '22 at 21:36
  • Thanks for the book recommendation also for the answer. @RichardCritten – Free_loader Aug 27 '22 at 21:47
  • @jkb Understood. – Free_loader Aug 27 '22 at 21:48

1 Answers1

2

The keyword "public" means that if an object of the class is instantiated, then any function/field defined with that keyword in the class is callable/accessible through the object. In contrast, "private" means that even if an object of the class is instantiated, the function/field is not accessible outside the class. For instance, obj.num is an invalid access of the field num of the object obj in your example.

However, since your question is "can the member functions be ONLY accessed by the objects of same class", to that I answer, "not necessarily".

For example, any class inherits from the class (like the class "foo" in your example) can access public/protected member functions as well. So if we do class bar : foo {}; bar child_obj; Then you could access the display() function by child_obj.display();

The other part of question consists in "why does the "display()" not call the member function rather it calls the non member function".

To this, it is because the calling of non-member function "display()" resolves the scope to be the global scope, rather than the scope of the member-function. Whereas, obj.display() resolves the scope to be the public member functions of the class foo.