Is it possible to pass constructor arguments to a function instead of the class object itself ?
According to the following code
#include <iostream>
#include <string>
class CL{
public:
int id;
CL(){
std::cout << "CL () Constructor " << std::endl;
}
CL(const char * name){
std::cout << " CL(const char * name) Constructor Called " << std::endl;
}
CL(int i){
id = i;
std::cout << "CL(int i) Constructor Called " << id << std::endl;
}
void print(){
std::cout << "print method Called " << id << std::endl;
}
};
void myfunc(CL pp){
pp.print();
}
int main(int argc,char **argv){
myfunc(10);
}
I passed integer to the function "myfunc" instead of class instance and it worked. I think it instantiated object on the fly.
the output is
CL(int i) Constructor Called 10
print method Called 10
is it such an ambiguity ? as for the same code if I overloaded the function "myfunc" as
myfunc(int i) {
std::cout << i << std::endl;
}
it will output 10
and ignore the function prototype that takes the class object
This is called implicit conversion and works for all constructors, that take a single parameter. In cases, where you don't want that, declare the constructor explicit:
class CL {
public:
int id;
CL(): id{0} {}
explicit CL(int i): id{i} {}
};
void myfunc(CL pp) {
// ...
}
int main(int, char) {
myfunc(10); // <- will fail to compile
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With