Reputation: 21
If I have a class:
class A {
public:
A();
~A();
int something();
}
class B {
public:
B() {a = new A();};
~B();
private:
A *a;
}
main() {
B x;
}
Is the only way to use object "a" in main is to have a getter for it?
class B {
public:
A getA() {return *a;};
private:
A *a;
}
And then if I wanted to set the private variable object, I would need a setter, and set it in main?
Edit: I updated class A, B, main a little. Main question is, what is the best way if I create an object of B in main. Can I access the function "something()" in anyway so information can be stored in private variable "a"? I know I can't do x.a.something() because "a" is private.
Upvotes: 0
Views: 591
Reputation: 1
"Is the only way to use object "a" in main is to have a getter for it?"
Yes.
"And then if I wanted to set the private variable object, I would need a setter, and set it in main?"
Again the answer is: Yes.
The purpose of making a class member variable private
is to encapsulate the data into the class, and making access only viable by using function members of this class. The simplest kind of function members are the getter and setter member functions.
They seem to be pretty useless for a naive point of view (at least as you could simply use a public
class member variable instead). But encapsulation means you don't need to change anything, if it turns out later, you'll e.g. need to survey setting new values for this member, might need to trigger recalculation of, or any action on other class member variables.
Your class declaration should look like follows (you don't need to use an A*
pointer usually)
class A {
};
class B {
public:
B() : a_() {}
const A& a() const { return a_; } // Getter
void a(const A& newValue) { a_ = newValue; } // Setter
private:
A a_;
};
And use it
int main() {
A a;
B x;
x.a(a); // Set the value
a = x.a(); // Get the value
}
To extend on your edit:
"Can I access the function
something()
in anyway so information can be stored in private variablea
? I know I can't dox.a.something()
becausea
is private."
You can't access that function directly from the classical getter function (as I had proposed above) like
x.a().something();
because something()
isn't a const
member function of class A
.
To allow manipulation you'll either need to declare the getter returning a non const reference (which actually breaks the mentioned encapsulation rules, and is discouraged because of this):
A& a() { return a_; } // Getter
or provide a member function in class B
, that delegates that call properly:
class B {
public:
// like all of my proposal from above ...
int doSomething() {
return a_.something();
}
private:
A a_;
};
Upvotes: 2