Accessing a class object outside the function it (the object) was declared in?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

using namespace std;

class Box {
   public:
      double length;   // Length of a box
      double breadth;  // Breadth of a box
      double height;   // Height of a box
};

int main() {
   Box Box1;        // Declare Box1 of type Box
   Box Box2;        // Declare Box2 of type Box
   double volume = 0.0;     // Store the volume of a box here
 
   // box 1 specification
   Box1.height = 5.0; 
   Box1.length = 6.0; 
   Box1.breadth = 7.0;

   // box 2 specification
   Box2.height = 10.0;
   Box2.length = 12.0;
   Box2.breadth = 13.0;
   
   // volume of box 1
   volume = Box1.height * Box1.length * Box1.breadth;
   cout << "Volume of Box1 : " << volume <<endl;

   // volume of box 2
   volume = Box2.height * Box2.length * Box2.breadth;
   cout << "Volume of Box2 : " << volume <<endl;
   return 0;
}


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.
Last edited on
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

class Box {
    double length, breadth, height;
public:
    Box(double l, double b, double h) : length(l), breadth(b), height(h) {}
    double volume() { return length * breadth * height; }
};

int main() {
    Box b(12, 13, 10);
    std::cout << b.volume() << '\n';
}

Last edited on
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.
Last edited on
Topic archived. No new replies allowed.