c++ doubt

ive just started learning c++ ... in c++ if


class emp
  {
      int a;
      
  public:
      void md(int r)
      {
       a=r;
       }
    int add(emp e2)
      {
    return(a+e2.a);// doubt !!!
    }
  }
void main()
  {
     emp e1,e2;
     e1.md(9);
     e2.md(15);
    int l= e1.add(e2);
    cout>>l;
     }
doubt!!! : how can a member function called by one object e1 access private members of another object e2.

Replies

  • jatin-phoenix
    jatin-phoenix
    deeksha,the operator used for cout is wrong. it should be <<.
  • shalini_goel14
    shalini_goel14
    Hi Diksha,
    A very good question. πŸ˜€

    I guess making the getters and setters for those variables .

    Ex
    Class Employee{
    private int privateVar;

    public void setPrivateVar(int privateVar){
    this.privateVar=privateVar;
    }

    public int getPrivateVar(){
    return privateVar;
    }

    }
    Note: Above lines is just a sample of code. It will not compile at all.

    So you can access those private methods of your e2 object from e1 instance right because they are public. Fair enough?

    This is a very good usage of OOPS concepts ok
  • ms_cs
    ms_cs
    The object e1 cannot access member of e2,here using e2 you r accessing the member..
  • MaRo
    MaRo
    this is the magical word for this.
  • pradeep_agrawal
    pradeep_agrawal
    Hi Deeksha,

    The code will not work for two reasons:
    1. The variable a of class emp is private and can't be accessed directly outside the class. C++ has three types of access specifier as public, protected, and private and if none of the access specifier is specified, the default is taken as private (as in your case).
    2. The code "cout>>l;", which should be "cout<
    Both will give a compile time error.

    To fix the item 1 either of the below approach can be
    1. Specify the access specifier for the variable 'a' as public (not a good practice).
    2. Create a public getter/setter function that return/set the value of the variable 'a' and then use these functions to do operations outside class.

    Let us know if you have more queries on this or if some item need more clarification.

    Regards,
    Pradeep
  • vivek.m
    vivek.m
    #include 
    using namespace std;
    
    class A
    {
    public:
        A(int r){a = r;}
        int add(A& e2)
        {
            e2.a = 7; //let's modify the private variable of another object..  :happy:
            return (a + e2.a);
        }
        int getValue(){return a;}
    private:
        int a;
    };
    
    int main()
    {
        A e1(9);
        A e2(15);
        cout<I have the same doubt as first poster. HOW? just how, e2 object is allowing access to its private variable 'a' inside e1 object. If 'a' were a static variable, then it could have been shared between two objects but not in this case where 'a'  is a local variable.

    #include 
    using namespace std;
    
    class B
    {
    public:
        B(int r){a = r;}
        int getValue(){return a;}
    private:
        int a;
    };
    
    class A
    {
    public:
        A(int r){a = r;}
        int add(B& e2)
        {
            e2.a = 7;
            return (a + e2.a);
        }
        int getValue(){return a;}
    private:
        int a;
    };
    
    int main()
    {
        A e1(9);
        B e2(15);
        cout<Here's the result is obvious compiler error where e2 does not allow access to private member inside e1.

    not able to figure out.. πŸ˜”
  • pradeep_agrawal
    pradeep_agrawal
    vivek.m
    #include 
    using namespace std;
    
    class B
    {
    public:
        B(int r){a = r;}
        int getValue(){return a;}
    private:
        int a;
    };
    
    class A
    {
    public:
        A(int r){a = r;}
        int add(B& e2)
        {
            e2.a = 7;
            return (a + e2.a);
        }
        int getValue(){return a;}
    private:
        int a;
    };
    
    int main()
    {
        A e1(9);
        B e2(15);
        cout<Here's the result is obvious compiler error where e2 does not allow access to private member inside e1.

    not able to figure out.. πŸ˜”
    As i specified in below post
    #-Link-Snipped-#
    that the variable 'a' of class 'B' is private and can't be accessed directly outside the class. Hence you are getting compile time error.

    To fix this either of the below approach can be taken:
    1. Specify the access specifier for the variable 'a' as public (not a good practice).
    2. Create a public getter/setter function that return/set the value of the variable 'a' and then use these functions to do operations outside class.

    Here in class 'B' you have defined a public getter function 'getValue' to get value of variable 'a' outside the class 'B' but you are not using it. Also you have not defined any setter for variable 'a'.

    Your class 'A' and 'B' should be modified as:

    class B
    {
    public:
        B(int r){a = r;}
        int getValue(){return a;}
        void setValue(int r) {a = r;}
    private:
        int a;
    };
    
    class A
    {
    public:
        A(int r){a = r;}
        int add(B& e2)
        {
            e2.setValue(7);
            return (a + e2.getValue());
        }
        int getValue(){return a;}
    private:
        int a;
    };
    
    Let me know if you face issue with above changes.

    -Pradeep
  • vivek.m
    vivek.m
    Hi Deesha,

    I have got the answer. Let's go back to the definition of 'private' variable
    A 'private' data member or member function can only be accessed by functions that are members of that class. It cannot be accessed by any function that is not a member function of that class.

    note the use of word 'class' which means that 'private' is class private and NOT object private as both of us were assuming till now.

    Probably, the rationale behind this is that any objects of that class can easily access that variable by simply using a get function for that variable. Moreover, in case of operator overloading, just look at the advantage of this:
    class A
    {
    public:
        A(int _a){a = _a; b=0;}
        A(int _a, int _b){a = _a; b = _b;}
        int modify(A& obj2)
        {
            obj2.a = 707; //this no longer surprises me. :happy:
            return obj2.a;
        }
        bool operator== (const A& obj2)
        {
            if( a == obj2.a && b == obj2.b)
                return true;
            return false;
        }
        A& operator+ (const A& obj2)
        {
            a += obj2.a;
            b += obj2.b;
            return *this;
        }
        int getValueA(){return a;}
        int getValueB(){return b;}
    private:
        int a, b;
    };
    
    void main()
    {
        A obj1(2);
        A obj2(10, 18);
        if(obj1 == obj2)
            cout<<"Equal";
    
        cout<<"a = "<Just look how in-convenient, not to mention the unnecessary function calls, it would have been to call getter function for each of the private variables inside operator overloading functions.

    Also, making private vars as class private may also depend on internal implementation of private variables also.

    More often than not, we are so much engrossed with public accessor/mutator that we use them even to access variables among objects!! At least, that's what I was doing for past so many years. πŸ˜’

    You sure are on right track to learning C++. you may find #-Link-Snipped-# helpful.

    Happy Learning and keep questioning (on CE )!

You are reading an archived discussion.

Related Posts

Hi all, 😁😁😁😁 Lets congratulate the PRIDE of our nation A.R Rahman Congo to Slumdog, won 8 oscars... Jai Ho! Aaja aaja jind shamiyaane ke taley Aaja zari waale neele...
hi, we will hav a discussion on clashes between them. both lawyers and police has to work together to solve a problem but they are creating problem and demolishing public's...
Name: Eze Engineering Trade: Student Manufacturing (automotive) Location: Melbourne Australia Occupation: Student (RMIT) Unemployed (left job to study) Lazy (dont cook my own meals) Work Experience: bout 5 years in...
As BlackBerry fans, you can't miss the BlackBerry Storm. At Nov 6th, 2008, the word on the street is that Best Buys around the colonies was start taking pre-orders for...
plzzzzzzzzzzz help us out πŸ˜• we need code for segmentation i.e if a scanned image( example😲f a torn piece )is given as input to the program then the code shud...