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

N

Neil

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!
 
T

Tigera

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.
 
N

Neil

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top