As an object of a smart pointer object accessing a member function of another class

I went through implementing a smart pointer. In the program below:

#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 works fine:

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

But ptrit is not a pointer to its class object CarSP. Now I doubt how it is ->used to access the Car member function with this. If I use ptr.Run(); But its giving an error,

Please, help.

0
source share
2 answers

Since I cannot include sample code in a comment, I am adding it here as an β€œanswer”, but this is not the correct answer. See patatahooligan's Link to Another Q & A Stack Overflow for a detailed explanation.

Here is an example for illustrative purposes:

#include <iostream>

static char const* hello = "hello";

struct Foo
{
  char const* something() const { return hello; }
};
struct Bar
{
  Foo foo;
  Foo const* operator->() const { return &foo; }
};
struct Quux
{
  Bar bar;
  Bar const& operator->() const { return bar; }
};
struct Baz
{
  Quux quux;
  Quux const& operator->() const { return quux; }
};
struct Corge
{
  Baz baz;
  Baz const& operator->() const { return baz; }
};

int main()
{
  Corge corge;

  // The -> resolves to a Foo const*, then called something() method.
  char const* s = corge->something();

  std::cout << "Result is: " << s << std::endl;
}
0
ptr->Run();

++ a->b (*a).b , a .

ptr . a , :

(ptr.operator->())->b

ptr - , operator->. operator-> Car.

,

(some pointer to Car)->b

++ ->. ->Run() 'd, .

0

Source: https://habr.com/ru/post/1693924/


All Articles