Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ Passing Variables Between Classes

  1. Sep 27, 2010 #1
    Hi,

    I am new to programming, but I think this is a simple error. For my programming code Im trying to pass a variable from a certain class to another class. The code is similar to below.


    Class 1
    PHP:


    #include "class2"

    Class2 class

    var1=1
    var2=2

    class.acceptingvariablesfrom1(var1 var2)

     
    Class 2
    PHP:


    class.acceptingvariablesfrom1(var1 var2)

    cout << var1 << endl;


     
    That is what my basic code looks like. I send my var1 and var2 to my acceptingvariablesclass however, how do I have them displayed. When I do my cout statement I get garbage. Am I doing something wrong? Class1 and Class2 are different .cpp files. In Class2 do I have to define var1 and var2 again even though they were defined in class1?

    I think this is a basic question but I just dont understand why I am getting garbage values?
     
    Last edited: Sep 27, 2010
  2. jcsd
  3. Sep 27, 2010 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    You need to use commas to separate the variables.
     
  4. Sep 27, 2010 #3
    I'm sorry, in my real code I had commas. I am just confused as to why garbage values print out.
     
  5. Sep 28, 2010 #4
    Post the actual code with declarations. This sample is nothing. (what are var1 and var2? ) And what param types is the function expecting?

    Garbage could be from anywhere in your code if you trashed a pointer somewhere.

    Create a small simple program that tests the classes, that will at least isolate whether it is the class or not.
     
  6. Sep 28, 2010 #5

    jtbell

    User Avatar

    Staff: Mentor

    Agreed. The best thing to do is construct a short, complete example program that can be pasted into a compiler and compiled successfully, and that demonstrates the problem.
     
  7. Sep 28, 2010 #6

    Borek

    User Avatar

    Staff: Mentor

    Besides, with this approach 9 times out of 10 you will find the problem by yourself.
     
  8. Sep 29, 2010 #7
    Yep. My daughter is a Comp Eng and she took a Comp Sci programming course, which was C at her University. I was shocked at how the prof. didn't teach the students proper style or technique. She stopped showing me her projects because I would get on her.

    Not initializing pointers? That is not a style preference, it is a must do.

    I think that is where the experience really comes into play; debugging.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook