assigning the address of a variable in c++
hi all,
im very new to c++ and programming, googled this but couldnt find an answer

if i want a instance of a variable, i can do this

int a = 10;
int & b (a);

so now the address of both a and b are the same, if i change one the other contains the same value as they are both the same address.

now i have a class like so

class testClass {
        int testInt;
        string testString; 

        testClass() :  testInt(0), testString("") {}  

        testClass(int& i, string& s) {
            testInt = i;
            testString  = s; 

what i want to do is create 2 instances of this class first and second like so

testClass first;
testClass second;

and here is where i dont know if i can do what i want.
i want to assign first.testString to a value such as "blah"
now i want the address of second.testString to be the same as first.tesString so that they are the same Adress and chaning one changes both. but i dont want the whole class to have the same address... i.e.

i can do
testClass first;
testClass &second(first)

but i dont want that, i want only one of the member variables to have the same addresses

is this possible or is there a better way to do this??


Recommended Answers

All 6 Replies

I think you want to declare testString as static. That way every instance of the class will reference the same instance of testString.

hi ancient dragon,
thanks for your reply, the thing is i want to create alot of instances of the class but i only want 2 of them to "share" the variable. so setting it as static wont work i think.

perhaps what i want is not possible but i dont know!!


try this out

class MyClass
	MyClass(int& xx) : x(xx){};

	int& x;

int main()
	int x;
	MyClass  c(x);

thank you,
thats great......

you have really helped me


just realized, this only works when construcing the class is there a way after the class is created?

int x = 200;
int z = 400;
MyClass a(x);
MyClass b(z);

// now i want b.x to share the address of a.x


AFAIK Must be done in the constructor.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.