Use of same class in multiple functions

I have a couple classes I am using throughout various functions. However, I keep creating a new instance of the class within each function like the following

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  auto Function1()
{
  ClassName classname;
  if (classname.something())
  { ... }
}

 auto Function2()
{
  ClassName classname;
  if (classname.somethingelse(somevariable))
  { ... }
}
  


What would be a more appropriate/efficient design here? Would it just be creating an initial instance of the class and passing that to the various functions or defining it as a private variable?
Do you use the classname variables for any other purpose other than those separate function calls?

You might not even need a class -- you could just have a function called something, and another function called somethingelse.

But even if you kept the ClassName object, it isn't necessarily an issue to begin with. Pushing/popping the stack is normally very fast. If ClassName were abnormally expensive to create, then there might be more discussion about further mitigations, but the problem as it currently stands is too abstract to give concrete advice on.
Hello michaelwilliams6511,

Without more of the program to look at and not knowing the correct context I am thinking you might mean something like this:
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
36
//Header files
#include <iostream>

auto Function1(ClassName& classname);
auto Function2(ClassName& classname);

int main()
{
    
    ClassName classname;

    SomethingForReturnValue = Function1(classname);

    SomethingForReturnValue = Function2(classname);

}

auto Function1(ClassName& classname)
{
    if (classname.something())
    {
        ...
    }

    return aValue;
}

auto Function2(ClassName& classname)
{
    if (classname.somethingelse(somevariable))
    {
        ...
    }

    return aValue;
}


Based on your bit of code when you define an object of the class in the function it becomes local to the function. First anything you may have done to the class elsewhere is not available with the new object and anything that you may change in the class is lost when the function ends and the variable/class is destroyed.

By defining in "main" and passing to the functions you are using the same object everywhere.

Andy
Thanks Handy Andy, that is very helpful and I believe points me in the right direction.
Topic archived. No new replies allowed.