Here is a sample code. I want to get address of int K that is in Volume() and also Length. How can i do that?
#include <iostream> using namespace std; class Box { public: Box(double l = 2.0) { length = l; } double Volume() { cout<<"Done"<<endl; int k=300; } public: double length; }; int main() { Box Box1(5); Box *ptrBox; ptrBox = &Box1; cout << "Volume of Box1: " << ptrBox->Volume() << endl; return 0; } How can i get the address of a variable in a class and a variable in a method in that class ?
int kis not a class member variable but a local variable (of functionBox::Volume()). To get its address is possible but very probably the prerequisite for Undefined Behavior. However, to accessBox::lengthis quite easy (as you made itpublic):Box1.lengthwould do the job as well asptrBox->length. (Didn't you learn this in your C++ book?) And, btw. your functionBox::Volume()has a non-voidreturn type but you didn'treturnanything. (That's Undefined Behavior as well.) Maybe, you intended toreturn k;but forgot to write it down?int kis a variable with automatic storage. That means its location is chosen every timeVolume()is called. And it no longer exists whenVolume()returns. At any moment, there may be many instances of thatk, or there may be none.int ks address but I wouldn't do you a favor with this.kis a local variable inBox::Volume()and its life-time (aka. existence) just ends when the execution returns from the call ofptrBox->Volume(). Returning the address ofkwould end up in a dangling pointer which points to nothing which may be accessed. (Hence, I mentioned Undefined Behavior as this is how it is called in C++ if you do something which you can do but you shouldn't do.)