how to access the public methods of a private data member?

Discussion in 'C++' started by Neil, Mar 6, 2007.

  1. Neil

    Neil Guest

    I am trying to access the public methods of a private data member in
    the composition. The following is my code. Am I right? If the return
    value of function in class Outer 'getInner()' is not reference, I
    cannot change the data member ia, why?

    //outer.h
    class Outer {
    class Inner {
    int ia;
    public:
    Inner(int val=0):ia(val) {}
    int get() const {return ia;}
    void set(int val){ia=val;}
    }in;
    public:
    Outer(int ival=0):in(ival){}
    Inner& getInner() {return in;} //What if Inner getInner(){...}
    };

    //main.cpp
    #include <iostream>
    #include "outer.h"
    using namespace std;

    int main(){
    Outer out;
    int a;
    a=out.getInner().get();
    cout<<"a="<<a<<endl;

    out.getInner().set(124);
    int b;
    b=out.getInner().get();
    cout<<"b="<<b<<endl;


    return 0;
    }


    Many thanks!
     
    Neil, Mar 6, 2007
    #1
    1. Advertising

  2. Neil

    Tigera Guest

    If you return something by value, you get a copy of the value. It
    doesn't matter whether the return type is an inner class or not.
    Though it surprises me that the code even compiles without the
    reference - I'd have thought the compiler would have complained of an
    incomplete type.
     
    Tigera, Mar 6, 2007
    #2
    1. Advertising

  3. Neil

    Neil Guest

    On Mar 5, 9:12 pm, "Tigera" <> wrote:
    > If you return something by value, you get a copy of the value. It
    > doesn't matter whether the return type is an inner class or not.
    > Though it surprises me that the code even compiles without the
    > reference - I'd have thought the compiler would have complained of an
    > incomplete type.


    Thank you!

    If I don't return by reference, does that mean it will create a copy
    of object Inner when 'out.getInner().set(124);' and create another
    copy of object Inner when 'b=out.getInner().get();'?

    So, even I reset the value, the new copy of object Inner is still
    initialized by 0, is that right?

    Neil
     
    Neil, Mar 6, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Charles A. Lackman
    Replies:
    1
    Views:
    1,439
    smith
    Dec 8, 2004
  2. SpamProof
    Replies:
    0
    Views:
    635
    SpamProof
    Oct 21, 2003
  3. DaveLessnau
    Replies:
    3
    Views:
    447
    Howard
    May 16, 2005
  4. Peng Yu
    Replies:
    3
    Views:
    1,116
    Simon Forman
    Sep 21, 2009
  5. Robert
    Replies:
    16
    Views:
    205
Loading...

Share This Page