reference to abstract class

前端 未结 4 479
一向
一向 2020-12-05 08:53

What does it mean when there is a reference to an abstract class? I found it in code and I can\'t understant it.

I thought that an abstract class can\'t be instantia

4条回答
  •  误落风尘
    2020-12-05 09:10

    class Abstract
    {
    public:
      virtual void foo() = 0;
    };
    
    class Implementation : public Abstract
    {
    public:
      void foo() { std::cout << "Foo!" << std::endl; }
    };
    
    void call_foo(Abstract& obj) { obj.foo(); } 
    
    int main()
    {
      Abstract *bar = new Implementation();
    
      call_foo(*bar);
    
      delete bar;
    }
    

    bar is a pointer to an abstract class. It can be dereferenced using the * operator and passed as a reference into call_foo, because that is what call_foo is asking for (Abstract* would be asking for a pointer, whereas Abstract& is asking for a reference).

    In the above, the reference to the abstract class is passed, and when foo() is called using the . notation (instead of the pointer -> notation), it prints Foo!, because that is what the Implementation does.

    Hope this helps.

提交回复
热议问题