What is difference between functions in main() and functions in a class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • simritsaini1982
    New Member
    • Aug 2008
    • 5

    What is difference between functions in main() and functions in a class

    Hello..
    Can anybody explain that how member functions of a class has direct access to the data members of the class vidout any need to declare them locally in the function body.
    As in main() we need to declare local variables inside the body of the function.
    as given below:-

    main()
    {
    int a;
    void display()
    {
    cout<<"enter value of a";
    cin>>a;
    cout<<"value of a is:"<<a;
    }
    }

    Above program shows syntax error: variable not declared



    But in..

    class ABC
    {
    private:
    int a;
    public:
    void display()
    {
    cout<<"enter value of a";
    cin>>a;
    cout<<"value of a is:"<<a;
    }
    };
    main()
    {
    ABC abc;
    abc.display();
    getch();
    }

    this program works well.

    Please Explain why so...
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    You can't nest functions as you tried to do in your first example; all functions
    reside at the outermost level. Member functions have access to all the member
    variables of that class by definition, i.e. that's one part that makes a class a
    useful thing for data encapsulation.

    kind regards,

    Jos

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Another thing is that everything in a class is a declaration and not a definition. Recall that declarations say something exists whereas definitions actually occuopy memory for that something.

      Those member variables do not exist until you create an object to the class. Then that object has a set of those variables. The member functions that are code in the class are not functions like those coded outside the class. The member functions coded inside the class are declaration and do not exist as functions until you call them. Then the compiler generates code that makes a copy of the member function and places it inline.

      Even so, if you declare a function within a member function, you will get your original error.

      Comment

      • simritsaini1982
        New Member
        • Aug 2008
        • 5

        #4
        Thanx for the information...

        Comment

        Working...