c++oop

Why Gun *gun=&machinegun is working, but *gun=&machinegun not?


I learn polymorphism in c++ and that's my code.

   class Gun
     {

       public:
       virtual void Shoot()
       {
          cout<<"BANG";
       }
      }

    class Machinegun:public Gun
 {

      public:
         void Shoot() override
        {
           cout<<"DRRRRRRRRRRRRRRR";
        }
     }

    int main()
    {
    Gun *gun;
    Machinegun machinegun;

    //Why I can't use      *gun=&machinegun;??????

    //It works when I write  Gun *gun=&machinegun;

    }

It's not the same thing *gun=&machinegun<=>*gun=&machinegun; ??? I see no difference Thanks


Solution

  • It seems you are confusing with the two uses of * .

    Gun * gun
    

    Here the * is used for defining a pointer of type Gun. Because it comes after the type Gun .

    If you are using * on an already defined object(pointer types specifically), like your second example it means to dereference that pointer, what comes back is the object that the pointer referenced to , and in your case Gun. A Gun object cannot be assigned with Machinegun* type

    What you probably wanted is

    Machinegun machinegun;
    Gun * gun;
    gun = &machinegun;