I'm still pretty new to C++, sorry if this question is stupid... although I've run into a lot of roadblocks this is the first time I can't find the answer through google online. So, I'm using a piece of code off of a tutorial on classes from https://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm
So Box1 has dimensions and Box2 has dimensions, and all is well and good within the main() function but as soon as I try to expand on this code and access either object's variables from another function outside of main() I'm getting errors that the object is undefined?
Is there a way I can access the variables within the class object from somewhere else in the program? Thanks for the help in advance.
There is actually more than one way to pass objects to functions depending on what you want to do. But the most common is to use a reference:
1 2 3 4 5 6
double calcVolume(const Box &b) { // use a const reference if you aren't modifying the object
return b.length * b.breadth * b.height;
}
// call it like this:
cout << calcVolume(box) << '\n';
Although in C++ you can make it a class method instead of a stand-alone function, in which case it would look like this:
Although in C++ you can make it a class method instead of a stand-alone function, in which case it would look like this:
To add: if the function can be implemented strictly in terms of the public interface of the class, it should be written as a non-member. The first way is better.