tags:

views:

73

answers:

4

Say I have a method, and within that method it instantiates a Person class:

void methodA()
{
    Person personObject;
}

How would I access that object's methods from within another method? I.e. something like:

void methodB()
{
    personObject.someMethod();
}

I realise it's a painfully nooby question :P

+4  A: 

Pass a reference to the other function.

void methodB(Person &personObject)
{
    personObject.someMethod();
}

void methodA()
{
    Person personObject;
    methodB(personObject);
}
Brian R. Bondy
Just to clarify methodB's personObject could be called anything at all. The name doesn't need to match that of methodA.
Brian R. Bondy
+1  A: 

You can't. The first Person object is a local object and disappears once outside the scope of the function. You'd need to make it part of the class for other methods to view it.

wheaties
A: 

You'll need to make personObject a member of the class. Also, if you must create personObject in methodA, rather than having it initialized in the constructor, then you'll need to dynamically create the object with new.

class MyClass
{
public:
    MyClass()
        : personObject(0)
    {
    }
    ~MyClass() 
    {
        delete personObject;
    }
    void methodA()
    {
        personObject = new Person();
    }
    void methodB()
    {
        personObject->someMethod();
    }
private:
    Person* personObject;
};
Andrew Walker
Of course, one needs to implement the copy-constructor and assignment operator as well.
GMan
A: 

Probably you want the personObject to be a member variable of your class:

class SomeClass {
   Person personObject;
public:
   void methodA();
   void methodB();
};

void SomeClass::methodA() {
    personObject = Person(123);
}

void SomeClass::methodB() {
    personObject.someMethod();
}
sth