I have a class (\"Class A\", we\'ll call it) which calculates the value of a pri
ID: 655490 • Letter: I
Question
I have a class ("Class A", we'll call it) which calculates the value of a private variable (which we can call numLoaves) with a public function. I need to use the value of numLoaves in a public function in Class B.
What is the best and most efficient way to pass in this value? I'm new to programming and have been looking for a solution for hours with no luck. Note: The function in Class B is void and must be this way. I can't use global variables or objects, pointers, friend functions or friend classes. The variable must be private.
Thank you!
Explanation / Answer
Look at it this way. You have two objects and you need a kind of medium for them to communicate with each other.A can go and ask B what he ate for breakfast.
A can do this by saying B.WhatDidYouEatForBreakfast() or shorter B.Breakfast(). The nice thing about it is that it doesn't need to go and check it's plates and dumpster (those are private) but the question is allowed (it's public). B, on the other hand, can say what he wants (will probably say fruits and vegetables, when in fact was chips and cola), but it better be the info that you're looking for (makes sure of this in the method body).
So, basically, you'll just have to have a public method in one of the classes with a return type of the private variable. This method will return the value of the private variable. Anybody can now call that object and find out what is going on.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.