0

I wrote down an example code to try to replicate the error I am getting in a school project about the scope of an object:

In file: classTest.cpp

#include "headerone.h"
#include "headertwo.h"

#include <iostream>

using namespace std;

int main() {

    ClassOne* pntrObj1 = new ClassOne;

    ClassTwo* pntrObj2 = new ClassTwo;

    pntrObj1->testClassOne();

    return 0;
}

In file: headerone.h

#ifndef HEADERONE_H
#define HEADERONE_H

#include "headertwo.h"

#include <iostream>

using namespace std;

class ClassOne {
    public:
        void testClassOne() {
            cout << "One Worked\n";
            pntrObj2->testClassTwo();
        }
};

#endif

In file: headertwo.h

#ifndef HEADERTWO_H
#define HEADERTWO_H

#include <iostream>

using namespace std;

class ClassTwo {
    public:
        void testClassTwo() {
            cout << "Two Worked";
        }
};

#endif

To be clear, the error is: pntrObj2 was not declared in this scope. The error comes from the file headerone.h

If I had to guess, I need to somehow pass the reference but I am not sure where to start for that. Any help is appreciated.

DavidJ85
  • 45
  • 4
  • 1
    Guessing your way into c++ is a really easy way to get turned off it. You should really start with a good book: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Fantastic Mr Fox Mar 09 '17 at 04:37

2 Answers2

1

The variable pntrObj2 is only visible inside the scope in which it was declared, in this case your function main(). In other words, only code inside the curly braces of main() would be able to use the name pntrObj2 to reference that variable. However you can pass that value to other pieces of code by making it the argument of a function call.

So maybe what you want to do is add an argument to the testClassOne() method, so you can pass in the value of pntrObj2. So pntrObj1->testClassOne(); would become pntrObj1->testClassOne(pntrObj2);, and where you define testClassOne you can add a corresponding parameter. I'll let you figure this out so as to not completely do your homework for you :)

Russel Simmons
  • 361
  • 1
  • 6
0

Here you include your file a lot of time and in testClassOne function, you do not declare pntrObj2

use

 void testClassOne() {
            cout << "One Worked\n";
            ClassTwo* pntrObj2 = new ClassTwo()
            pntrObj2->testClassTwo();
        }

insteed of

 void testClassOne() {
            cout << "One Worked\n";
            pntrObj2->testClassTwo();
        }