Ángel
Ángel

Reputation: 145

How to create an object in one method and use it in another

This is the simplified version of my code:

#include <iostream>

using namespace std;

class ClassA {
    public:
        void method1A(){
            cout << "Hello World." << endl;
            }
        void method2A(){
            cout << "Bye." << endl;
            }       
};

class ClassB {
    public:
        void method1B(){
            ClassA objectA;
            objectA.method1A();
            }
        void method2B(){
            objectA.method2A();
            }
};

int main() {
    ClassB objectB;
    objectB.method1B();
    objectB.method2B();
    return 0;
}

The error is: ‘objectA’ was not declared in this scope, I suppose it's because the method "method2B" does not have access to the object "objectA" -yep, I'm learning c++ ^^-. How it works without move the "objectA" object declaration from "method1B"?

Upvotes: 0

Views: 82

Answers (3)

mike bayko
mike bayko

Reputation: 375

You could dynamically allocate space for a new ClassA on the heap and then return a pointer to the start of that memory:

#include <iostream>

using namespace std;

class ClassA {
public:
    void method1A(){
        cout << "Hello World." << endl;
    };
    void method2A(){
        cout << "Bye." << endl;
    };       
};

class ClassB {
public:
    ClassA * method1B(){
        ClassA * ObjectA = new ClassA;
        ObjectA->method1A();
        return ObjectA;
    };
    void method2B(ClassA * objectA){
        objectA->method2A();
    };
};

int main() {
    ClassB objectB;
    ClassA * objectA = objectB.method1B();
    objectB.method2B(objectA);
    delete objectA;
    return 0;
};

I hope this helped.

Upvotes: 1

Engineero
Engineero

Reputation: 12908

You need to declare the member object outside of your methods:

class ClassB {
    public:
        ClassA objectA;
        void method1B(){
            objectA.method1A();
            }
        void method2B(){
            objectA.method2A();
            }
};

That way it is accessible to everything inside the class. If you do not want it accessible outside of the class, make it private or protected instead:

class ClassB {
    public:
        // Your public declarations
    private:
        ClassA objectA;
};

Upvotes: 2

Yuval Ben-Arie
Yuval Ben-Arie

Reputation: 1290

You have two options:

  1. put objectA as a member of ClassB
  2. create another ClassA inside method2B (like you did in method1B)

Upvotes: 2

Related Questions