0

In a program I'm making, I'm trying to get a certain class to pass data to another class's function as a parameter. This data happens to be a variable from the first class's member enumerator. But I'm getting a lot of errors. The code below is an example of what I'm trying to do. I've added the errors in the comments above their lines:

main.cpp:

#include "A.h"

int main(int argc, char* args[]) {
    A a;

    a.callFunctionB();

    return 0;
}

A.h:

#pragma once
#include "B.h"

class B;

class A {
public:
    enum Enumerator {x, y, z};
    void callFunctionB();
private:
    //C2146: syntax error : missing ';' before identifier 'b'
    //C4430: missing type specifier - int assumed.
    B b;
    Enumerator e = x;
};

A.cpp:

#pragma once
#include "A.h"

void A::callFunctionB() {
    //C2660: 'B::functionB' : function does not take 1 arguments
    b.functionB(e);
}

B.h:

#pragma once
#include "A.h"

class A;

class B {
public:
    //C2653: 'A': is not a class or namespace name
    //C2061: syntax error : identifier 'Enumerator'
    //C2653: 'A' is not a class or namespace name
    void functionB(A::Enumerator e);
};

B.cpp:

#pragma once
#include "B.h"
#include <iostream>

void B::functionB(A::Enumerator e) {
    std::cout << "It worked! Enumerator variable 'x' was passed to function B." << std::endl;
}

Why can't I send the variable of one class's member enumerator as a parameter to another class's function?

  • 1
    I think you have an include problem here. `B.h` includes `A.h` but `A.h` also includes `B.h`. – Telokis Jun 09 '15 at 11:07

1 Answers1

3

You have a circular dependency problem. Your files can include each other all they want, but the

#pragma once

at the top means that only one sees the other one; not that each sees the other.


There are several ways to go here.

One way would be to remove the enumerator of A outside the class (possibly to some more private namespace). In general, you want your classes to "know as little as possible" about each other in any case.

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • Thanks for your answer. That's a good link :) But I'm wondering if I should forget trying to use the enumerator for a parameter in my program. I'm curious about the use of namespaces though: In this example, if the enumerator is needed by both class A and class B functions, where would you put the namespace? The namespace can only be used in files that include the file where it was created, right? –  Jun 10 '15 at 07:32
  • It really depends on the case, but perhaps you could try with some header file that both classes include. That would break the circular dependency. – Ami Tavory Jun 10 '15 at 07:33