-1

my question is why the object becomes invisible or uncountable after passing another object to a method in my object?

it's H page

class test
{
    public:
        test();

        void setNumber(int number);
        test add_test (test t1);
        int GetCounter();

        virtual ~test();

    private:
        int number;
        int static counter;
};

#endif

it's class page

int test::counter = 0;

test::test()
{
    counter++;
}

test::~test()
{
    counter--;
}

void test::setNumber(int n)
{
    number = n;
}

test test::add_test(test t1)
{
    test result;
    result.number = number + t1.number;
    return result;
}

int test::GetCounter()
{
    return counter;
}



it's the main page

#include <iostream>
using namespace std;

int main()
{
    test t1;
    test t2;
    test t3;

    t1.setNumber(5);
    cout<<t1.GetCounter()<<"\n";

    t2.setNumber(5);
    cout<<t2.GetCounter()<<"\n";

    t3 = t2.add_test(t1);
    cout<<t3.GetCounter()<<"\n";
}

it all happens after I put "add_test" methode to object (t3) then became t3 like invisible which can't be counted as an object

how does the output = (3 3 2) if there's 3 objects (t1 ,t2, t3) why didn't it return 3 3 3

  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jason Dec 04 '22 at 04:50
  • Because your code is not incrementing `counter` every time an object is created, but is decrementing `counter` every time one is destroyed. `t2.add_test(t1)` creates a copy of `t1` - using an implicitly generated copy constructor that does not increment `counter` - and `counter` is decremented when that copy is destroyed. Look up "rule of three" or (in C++11 and later) "rule of five" for more information. – Peter Dec 04 '22 at 05:13

1 Answers1

1
t3 = t2.add_test(t1);

This makes a new temporary class test object to pass to add_test (so there are actually four test objects in the program). Since you didn't define a copy constructor, the default copy constructor is used, and it doesn't increment your counter. But when this temporary is destructed, it calls your destructor (there is no other) which does decrement the counter.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82