Matteo
Matteo

Reputation: 8142

use enum type from another class

I've read all the suggestions I've found in the following links

  1. c++ typedef another class's enum?
  2. http://forums.devarticles.com/c-c-help-52/how-to-use-enum-when-it-is-in-another-class-17773.html
  3. http://forums.codeguru.com/showthread.php?t=435215
  4. How do I use the Enum value from a class in another part of code?

but still wasn't able to find a solution to my problem:

I need to construct an object of class A (whose constructor expects as an input parameter an enumerative type of that class) from inside a function of an object of class B

Here are the code snippets:

File A.h:

Class A{
    public:
       enum FileType{TEXT, BIN};

       /*! This constructor initializes the data from a given file
        *  (binary, text, image). 
        */
       A(const std::string& filename, FileType type);

}

File A.cpp:

A::A(const std::string& filename, FileType type){
 ...
}

File B.h:

Class B{

    private:
       A objectOfClassA;

    public:
       enum FileType{TEXT = A::FileType::TEXT, BIN = A::FileType::BIN}; //<----THIS IS NOT WORKING!           
       foo_func(const std::string& filename, FileType type);

}

File B.cpp:

void B::foo_func(const std::string& filename, FileType type){

    this->objectOfClassA(filename, type); //should construct an object of class A
    ... //do stuff with objectOfClassA
}

File main.cpp:

int main(int argc, char** argv) {

    B objectOfClassB;
    objectOfClassB.foo_func("file_path", foo_func.TEXT);

}

By trying to run main program I get this error from compiler in the B.cpp file at line of function foo_func:

no match for call to ‘(A) (std::basic_string, B::FileType&)’

which means that I'm not using the correct enum type to call A class constructor, but how can I fix this?

What am I doing wrong?

Upvotes: 3

Views: 8118

Answers (1)

Eddie Edwards
Eddie Edwards

Reputation: 428

B::FileType and A::FileType are different types. You need to typedef A::FileType FileType inside B to alias the types correctly so they are interchangeable. Otherwise B::FileType is an enum which is structurally the same as A::FileType, but unrelated in the type system. This answers your primary question.

Fixing this still won't permit your code to compile, however, and this is not what the error is complaining about.

objectOfClassA is already constructed inside foo_func. Calling this->objectOfClassA(filename, type) is an attempt to use the overloaded () operator on the object; this operator does not exist so the code cannot compile. You can only construct objectOfClassA via B's constructor using initializer notation, e.g.

B::B(const std::string& filename, FileType type) : objectOfClassA(filename, type)
{
  ...
}

Then in main you would do this:

B objectOfClassB("file_path", B::TEXT);

Step through in the debugger to see the control flow.

Upvotes: 7

Related Questions