vendredi 23 février 2018

How object of smart pointer object accessing member funtion of other class

i have gone through the smart pointer implementation. In the below program

#include <iostream>

using namespace std;

class Car{

public:
    void Run(){
        cout<<"Car Running..."<<"\n";
    }
};

class CarSP{

    Car * sp;

public:
    //Initialize Car pointer when Car 
    //object is createdy dynamically
    CarSP(Car * cptr):sp(cptr)
    {
    }

    // Smart pointer destructor that will de-allocate
    //The memory allocated by Car class.
    ~CarSP(){       
        printf("Deleting dynamically allocated car object\n");
        delete sp;
    }

    //Overload -> operator that will be used to 
    //call functions of class car
    Car* operator-> ()
    {    
        return sp;
    }
};


//Test
int main(){

    //Create car object and initialize to smart pointer
    CarSP ptr(new Car());
    ptr.Run();

    //Memory allocated for car will be deleted
    //Once it goes out of scope.
    return 0;
}

This program is working fine with

CarSP ptr(new Car());
ptr->Run();

But ptr is not a pointer its object of the class CarSP Now my doubt is how -> is used for accessing Car member function with this. If i am using ptr.Run(); its giving error

Please help

Aucun commentaire:

Enregistrer un commentaire