returning an abstract class from a function

后端 未结 7 809
甜味超标
甜味超标 2020-12-03 07:07

Is it possible to return an abstract class(class itself or a reference, doesn\'t matter) from a function?

7条回答
  •  不知归路
    2020-12-03 07:31

    You can't return abstract class itself in the funtion return, but abstract class point and abstract class reference are both OK.

    The only thing you need to worry is if you return by point, will the caller own the object and release, if you return by reference, be careful to return funtion's local variable, it compiles fine but it will crash. The function local variable will be released after the function call, like the following code, it will crash at line "a.print();". Hopefully it make sense.

    class A {
    public:
      virtual void print() = 0;
    };
    
    class B : public A {
        
        public:
        void print()
        {
            cout << "print";
        }
        
        A& GetA() {
            
            B b;
            return b;
        }
    };
    
    int main()
    {
        cout<<"Hello World";
        
        B b;
        A &a = b.GetA();
        a.print();
        return 0;
    }
    

提交回复
热议问题