Search code examples
c++classvisual-c++new-operator

Can you instantiate a class and then assign a different class to it using new (e.g. class1 name = new class2)


I was watching a c++ tutorial about the "->" operator on youtube (the link ) in 2:48 of the tutorial. He wrote the code

int main()
{ScopedPtr entity = new Entity();}

from what I understand about instantiating class, the class behind new keyword should be the same as the class you are instantiating. Pls explain how this work and why it work.

FYI: I'm a beginner to coding and I do not have have guide books or anything I'm currently learning C++ from the youtube channel called Cherno, and whenever I don't understand something I just search up on the internet and go into website


Solution

  • Yes it may happen for instance when you create a pointer to an implementation of your classes where ScopedPtr is a pointer to the implementation of Entity.

    You could have some documentation here or here

    #include <iostream>
    
    class Entity
    {
    public:
        Entity(){}
        //only for test
        void print()
        {
            std::cout << " print";
        }
    };
    
    class ScopedPtr
    {
    public:
        ScopedPtr(Entity* d) { implem = d;}
        ~ScopedPtr(){ delete implem;}
    
        //only for test
        void print()
        {
            implem->print();
        }
    private:
        Entity* implem;
    };
    
    int main()
    {
        ScopedPtr entity = new Entity();
        entity.print();
    }