#class constructor overload with same amount of arguments but diffrent types

24 messages · Page 1 of 1 (latest)

sick seal
#

I want to create a class with multible constructors, both taking one argument but of diffrent types, g++ gives me an error that the second constructor doesnt exist

example: ```cpp
class TestClass {
public:
TestClass(const char* someArg) {
// do something
}
TestClass(int someArg) {
// do something
}
TestClass(char* someArg) {
// do something
}
// ...
};

int main() {
TestClass("a"); // works fine
TestClass(1); // gives an error

return 0;
}


the error is: (some int is a variable of type int) ```
main.cpp:52:22: error: conflicting declaration 'TestClass someInt'
     TestClass(someInt)
lone gullBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

sick seal
#

this works: ```cpp
TestClass(1);

#

but this doesnt: ```cpp
int someInt = 1;
TestClass(someInt);

spare sinew
#

apparently this gets parsed as a declaration of someInt of type TestClass but constructing it like this fixes it TestClass{someint};
Clang calls this a variation of the vexing parse which cant happen with braced initialization

swift harbor
#

if you want to have a new variable, you must give it a name

#

because otherwise, assuming the parsing was as you intended it to be, you'll create a temporary that will immediately die

sick seal
#

oh so like: new SomeClass(someValue) in java?

swift harbor
#

chris already gave you an alternative syntax to get that working

#

well no, you don't use new in c++ like you use new in java

sick seal
#

but this is about the same right?
(java) ```java
new SomeClass(someValue);

(c++) ```c++
SomeClass(someValue);
swift harbor
#

no

#

SomeClass(someValue); is SomeClass someValue;

sick seal
#

oh

swift harbor
#

which is why you have an error

sick seal
#

thank you for explaining :)

swift harbor
#

that's what me and chris told you in our first messages

sick seal
swift harbor
#

which is still text, but fair enough

sick seal
#

thank you SlyBach and Chris :)

spare sinew
lone gullBOT
#

@sick seal Has your question been resolved? If so, run !solved :)

sick seal
#

!solved