0

So I have 2 functions and 1 class. with 1 function I want to Set value's of the integers stored in a class. with the other function I want to use these value's again. I'm using pointers as I thought this would be saved on Memory address's across the whole program.

#include <iostream>
using namespace std;


void Function1();
void Function2();
class TestClass
{
public:
    TestClass();
    ~TestClass();
    void SetValue(int localValue)
    {
        *value = localvalue;
    }
    int GetValue()const
    {
        return *value;
    }
private:
    *value;
};

TestClass::TestClass()
{
    value = new int(0);
}

TestClass:
~TestClass()
{
    delete value;
}

int main()
{
    TestClass *tommy = new TestClass; //this didn't work,
    //couldn't use SetValue or Getvalue in functions
    Function1();
    Function2();
    return 0;
}

void Function1()
{
    int randomvalue = 2;
    TestClass *tommy = new TestClass; //because it didnt work in main, i've put it here
    tommy->SetValue(randomvalue);
}

void Function2()
{
    TestClass *tommy = new TestClass;
    cout << tommy->GetValue();
            << endl; //this gave a error, so I put the above in    again
    //but this returns 0, so the value isn't changed
}

So, got a solution for me? I didn't got any compile errors, but the value isn't changed, probably because the destructor is called after Function1 has been completed. so how do I do it?

2
  • Please be more specific. What exactly didn't work? Did you get an error message (if so, post it)? Did you get unexpected behavior (if so, describe it)? Commented Oct 20, 2013 at 22:50
  • Have you heard of indentation. Makes things readable Commented Oct 20, 2013 at 22:55

3 Answers 3

1

You need to pass your tommy from main() to each of your functions, not create a new one in each time, otherwise you're just losing the new Testclass objects you're creating in your functions, and actually here getting memory leaks because you use new.

Something like:

void Function1(TestClass * tommy) {
    int randomvalue =2;
    tommy->SetValue(randomvalue);
}

and then in main():

int main() {
    TestClass *tommy = new TestClass; 
    Function1(tommy);
    std::cout << tommy->GetValue() << std::endl;  //  Outputs 2
    delete tommy;
    return 0;
}

This is an odd use case, though - this would be the kind of thing you'd expect member functions to do. This would be better:

int main() {
    TestClass *tommy = new TestClass; 
    tommy->SetValue(2);
    std::cout << tommy->GetValue() << std::endl;  //  Outputs 2
    delete tommy;
    return 0;
}

without the need for Function1() and Function2(). Either way, you're going to have to fix:

private:
*value;

in your class, as someone else pointed out.

Sign up to request clarification or add additional context in comments.

6 Comments

@Chad: Why indeed? Ask the OP, he said in his question he wanted to use them. That being said, I don't particularly agree that pointers are always to be avoided, but without seeing a real use case (meaning I doubt this is the entirety of the program he wants to write), there's not much I can do about forming a view on whether they're best here or not.
I realize that SO is about answering direct questions, but this question as posted is obviously from someone with not much experience in C++. He's using pointers because he "thought this would be saved on Memory". We should be working to not just make "code that works", but code "that is better".
@Chad: As I edited, I doubt what he posted is intended to represent the complete functionality of his program. Without knowing what he's trying to do, it's probably best not to try to prejudge what would be "better", here. There are certainly places where pointers are the ideal solution, perhaps what he's trying to write is one of them, for all we know. We do tell people to post the shortest compilable example they can do demonstrate the problem.
@user2901207: You're welcome. Chad's advice is not bad, gratuitous use of pointers does tend to be avoided in modern C++, although I don't hold to the view that strenuous steps should be taken to avoid them.
It's pretty obvious I'm new to programming, ofcourse this is part is just to point out my problem and not my entire program. The reason I use pointers is because I've learned that pointers make the program run faster in the end, because you can delete them again. And I just want to know how to use them so for this program (which I'm making to improve my skills) I chose to use pointers
|
0

you are not passing your TestClass to either function so they functions can't see the tommy object you made. Then in each function you create a new local variable that just happens to have the same name as your local variable in main... They are all independent objects

1 Comment

ah, and as I answer this, below someone wrote the same thing with code. Choose his!
0

Every time you write new TestClass, you are quite literally creating a new instance of a TestClass object. The new instance is not related to any existing instances in any way, except for being of the same type. To make the single instance of TestClass be "the one" being used by your functions, you need to pass it in as an argument to those functions.

Also -- Don't use pointers unless it is absolutely necessary.

Here's a cleaned up example of your code that accomplishes what it appears you were trying.

class TestClass
{
   int value;

public:
   TestClass() : value(0)
   {}

   int GetValue() const { return value; }
   void SetValue(int x) { value = x; }
};

// takes a "reference", works somewhat like a pointer but with
// some additional safety guarantees (most likely will not be null)
// This will modify the original passed in TestClass instance.
void SetRandomValue(TestClass& tc)
{
   int random = 2; // not really random...
   tc.SetValue(random);
}

// take a const reference, similar to above comment, but a const
// reference cannot be modified in this scope
void Print(const TestClass& tc)
{
   std::cout << tc.GetValue() << "\n";
}

int main()
{
   // create a TestClass instance with automatic storage duration
   // no need to use a pointer, or dynamic allocation
   TestClass tc;

   // Modify the instance (using reference)
   SetRandomValue(tc);

   // print the instance (using const reference)       
   Print(tc);

   return 0;
}

3 Comments

Why has this been downvoted? It's perfectly valid and good advice.
It wasnt me who downvoted but this does not answer OP why he had to write new TestClass 3 times.
@Agent_L, true enough. Edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.