0
votes

In the main function in this code what does this (ScopedPtr ent = new Entity()) mean Why we are not using (ScopedPtr*) as per C++ instantiating style

#include<string>

class Entity
{
public:
    Entity()
    {
        std::cout << "Created Entity!" << std::endl;
    }
    void Print()
    {
        std::cout << "Print" << std::endl;
    }
    
};

class ScopedPtr
{
private:
    Entity* m_Ptr;
public:
    ScopedPtr( Entity* ptr) 
        : m_Ptr(ptr)
    {}

    /*ScopedPtr()
    {   
        std::cout << "Hello"; 
    }*/

    ~ScopedPtr()
    {
        std::cout << "Deleted Pointer";
        delete m_Ptr;
    }
};

int main()
{
    {
        ScopedPtr ent = new Entity();

And why the ScopedPtr(Entity Constructor) Didn't take a Entity* parameter and the code ran successfully

    }
    std::cin.get();
}
2
the constructor is ScopedPtr( Entity* ptr). It does have an Entity* parameter - M.M
read about the keyword explicit - Waqar
I am Talking about ScopedPtr ent = new Entity() in this code it didn't take a actual parameter in the main function. - Ishit Jaiswal

2 Answers

3
votes
ScopedPtr ent = new Entity();

The right-hand-side is a value of type Entity*, regardless of the details. So it could be written as

Entity* t = new Entity();  // doesn't matter what it's = to, just note its type.
ScopedPtr ent = t;

Now you have a variable definition T x = y; where y is not of type T. So, it implicitly converts to the correct type, and this is really

ScopedPtr ent = ScopedPtr(t);

The = here is initialization not assignment, so ent is initialized with that (converted) right-hand-side.

1
votes

Why we are not using (ScopedPtr*) as per C++ instantiating style

Because new is not required to create objects. The whole point of ScopedPtr is to tie the lifetime of an object with dynamic storage duration ("on the heap") to another with automatic storage duration ("on the stack")