Is a class created in a method remembered?


I'm new to C++, but I've been writing C for several years. I'm trying to learn C++, but on my own (unstructured), and have some questions:

Suppose I declare two classes,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class class1
{
public:
   class1();
   void setvar1(int pVar) {var1 = pVar;}
   int getvar1() {return var1);}
   void setvar2(char pVar) {var2 = pVar;}
   char getvar2() {return var2);}
.
.
.
private:
   int var1;
   char var2;
}


(with appropriate method definitions,) and

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class class2
{
public:
   class2();
   int do_interesting_things();
.
.
.
private:
   int var1;
}

class2::do_interesting_things()
{
   class1* test_case = new class1();
   test_case::setVar1(1);
   test_case::setVar2('x');
.
.
.
   return;
}


When class2::do_interesting_things() is called, a new instance of class1 is created, and the variables var1 and var2 are assigned some values. Upon return from this function, are the variables in class1 (that is, in test_case) forgotten?

Also, what's the difference between
 
  class::method();

and
 
  class->method();


Thanks in advance.
Since test_case is a local variable it's destroyed when the function is done.
The memory for class1 is still there just not longer accessible -> memory leak.

Also, what's the difference between
The first is a [static] function call of a specific class
The second one calls the last overridden function (you need a variable not a class for this)

This applies basically to virtual function

By the way:
1
2
   test_case::setVar1(1); // Invalid: you can call a function statically of a class not a variable
   test_case::setVar2('x'); // see above 
Last edited on

Thanks coder777, I think I get it now. I should delete test_case before returning.

And I should have used
1
2
test_case->setVar1(1);
test_case->setVar2('x');

You have now:
1
2
3
4
5
6
void class2::do_interesting_things()
{
   class1* test_case = new class1();
   test_case->setVar1(1);
   delete test_case;
}


You could have non-dynamic local object:
1
2
3
4
5
void class2::do_interesting_things()
{
   class1 test_case;
   test_case.setVar1( 1 );
}


Or even:
1
2
3
4
5
6
class1::class1( int a ) : var1( a ) {}

void class2::do_interesting_things()
{
   class1 test_case{ 1 };
}



Edit:
C++11 has <memory> to manage the dynamically allocated objects, so the first example rewritten:
1
2
3
4
5
6
7
#include <memory>

void class2::do_interesting_things()
{
   std::unique_ptr<class1> test_case( new class1 );
   test_case->setVar1(1);
}

Last edited on
Topic archived. No new replies allowed.