Class enumerator values cannot be passed as parameters to another class's function

201 views Asked by At

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

There are 1 answers

2
Ami Tavory On BEST ANSWER

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.