Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP: Passing primitive types to function that expects objects

Tags:

c++

oop

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

like image 905
becks Avatar asked Apr 15 '26 13:04

becks


1 Answers

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
}
like image 102
cdonat Avatar answered Apr 18 '26 04:04

cdonat