Reputation: 8142
I've read all the suggestions I've found in the following links
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 ofclass 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
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