1

I've been working on this issue for awhile now. I"m just looking to pass a one character value from one class to another

In my header file I have a variable declared:

 extern char variable1; 

in class1.cpp i have the same variable declared:

char variable1 = 'N'; 

in class2.cpp i have the same variable declared: I don't initialize this due to the logic required for the Y/N is in class1.cpp

 char variable1; 

My assumption on how this would work is that I would go through the logic to set it to a Y or keep it an N as initizlied in class1, once the function is finished, I would click the button on the form to go to the next class and since they all have the same name and the file name is in the header file with the keyword extern it would pass the values back and forth, is my thinking wrong? I'm still new to visual c++ so i'm just trying to learn.

4
  • i think we need more details, it's not clear actually Commented Apr 26, 2013 at 14:48
  • 1
    Haven't you got a build error when you declared the variable again in class2.cpp ? All you have to do is include the header in class2.cpp and define the variable only once ( which you are already doing in class1.cpp ). Commented Apr 26, 2013 at 14:50
  • I'm not sure what else you would need. All i've been reading is that you need to declare the variable in the header file as extern then declare the file again in all the .cpp classes you are planning on using the variable in. JUst looking on how to actually pass the data, currently it's not passing it between the two classes Commented Apr 26, 2013 at 14:50
  • 1
    Why is this tagged winforms? Also, if you're just using variable1 to represent a yes/no state, then bool is probably more appropriate. Commented Apr 26, 2013 at 14:56

2 Answers 2

2

char variable1; without the extern is not a declaration, it's a definition. This means you're defining the variable in both class2.cpp and class1.cpp, which is illegal. Define it in only one .cpp file. The other .cpp files should then #include the header containing the declaration, which will give them access to the variable.

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

2 Comments

That was my issue. My understanding of passing variables wasn't quite right, thanks everyone!
@Criel Just to clarify - you're not passing anything anywhere. You just have a global variable in your program, and you're accessing it from two different locations. Passing means giving something as an argument to a function, and is generally a better design than shared global state.
0

If you declare extern char variable1; in class1's cpp file, and define char variable1; in class2, you should be able to do what you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.