Reference through classes?

I am entering a string for the class. How do I get set the values for that string permanently? For example, I want to set it like how I would through references, but how would I even begin doing that using a string through class?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// The Learning Process.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

typedef short int UINT;

class jimboClass
{
public:
	std::string myString;//i want this to be set to whatever user types
};

void printString()
{
	jimboClass objectPrintString;
	std::cout << "From printString(): " << objectPrintString.myString << std::endl; //this line prints nothing, but i want it to print the same thing as jimboObject.myString
}

int main()
{
	jimboClass jimboObject;
	std::getline(std::cin, jimboObject.myString);
	std::cout << "From main(): " << jimboObject.myString << std::endl;
	printString();
    return 0;
}
You may need to learn about scope.
http://en.cppreference.com/w/cpp/language/scope

objectPrintString and jimboObject are in two different scopes.

After learning scope, you may be interested in static members.
http://en.cppreference.com/w/cpp/language/static
Last edited on
jimboObject and objectPrintString are two different instances.

You have several options:

1) Pass jimboObject to your printString function as an argument.
1
2
3
4
5
6
void printString (const jimboClass & objectPrintString)
{ std::cout << "From printString(): " << objectPrintString.myString << std::endl; 
}

// In main:
  printString(jimboObject);


Or 2) (preferred) make printString() a member of jimboClass.
1
2
3
4
5
6
7
8
9
10
// After line 13:
    void printString();

// Change 16-20:
void jimboClass::printString()
{  std::cout << "From printString(): " << myString << std::endl; 
}

// change line 27:
  jimboObject.printString();


3) (advanced) overload jimboClass' << operator.
1
2
3
4
5
6
7
8
9
10
11
// After line 13
  friend std::ostream & operator << (std::ostream & os, const jimboclass & jimboInstance);

// Change 16-20:
std::ostream & operator << (std::ostream & os, const jimboclass & jimboInstance)
{ os << jimboInstance.myString;
   return os;
}

// Replace line 27:
    std::cout << jimboObject << std::endl;


BTW: I would not use static for this.










Last edited on
AbstractionAnon wrote:
BTW: I would not use static for this.
dasani885 wrote:
How do I get set the values for that string permanently?

This sounds to me like the OP wants a static final class member, but I have to agree with you after seeing your examples that the OP is trying to accomplish something else.
Topic archived. No new replies allowed.