Wednesday, June 26, 2024

Return Type Overloading in C++

Small tricks to accomplish return type overload in c++. In cpp one can not overload return type. If you follow this trick you can overload return type using operator overloading :)


struct Car {

    string name;

    string brand;

};


struct Bus {

    string name;

    string brand;

};


struct Transport 

{

    Car get_car()

    { 

        Car oCar;

        oCar.name="Axio"; 

        oCar.brand="Toyota";

        return oCar; 

    }

    

    Bus get_bus()

    {

        Bus oBus;

        oBus.name="Greenline"; 

        oBus.brand="Hundai";

        return oBus; 

    }

    

    auto get_transport()

    {

        struct result

        {

          Transport * trans;

          operator Car() { return trans->get_car(); }

          operator Bus() { return trans->get_bus(); }

        };

        

        return (result{this});

    }

};


int main() {

    

    Transport tt;

    Car myCar = tt.get_transport();

    Bus myBus = tt.get_transport();

    

    cout << myCar.name << " == " << myCar.brand << endl;

    cout << myBus.name << " == " << myBus.brand << endl;


    return 0;

}


============

You can not use below code it will get compile error:

struct Transport 

{

    Car get_transport() { return (Car{});}

    Bus get_transport() { return (Bus{});}

};

No comments:

PC Magazine Tips and Solutions

PC World: Latest Technology News

PCWorld.com - Most Popular Downloads of the Week