none
return abstract base class type pointer from the derived class RRS feed

  • Question

  • I have a big doubt on how to return pointer instance of abstract base class from its derived class.

    For example,

    in Xerces data object model, DOMDocument is an abstract class and hence it cannot be instantiated.(Error: DOMDocument* doc=new DOMDocument()).

    Then how, the class XercesDOMParser can return DOMDocument* type without the instantiation of DOMDocument class.

    XercesDOMParser* myParser=new XercesDOMParser();

    DOMDocument* doc=myParser->getDocument();



    Saturday, June 4, 2011 8:13 AM

Answers

  • I have a big doubt on how to return pointer instance of abstract base class from its derived class.
     
    For example,
     
    in Xerces data object model, DOMDocument is an abstract class and hence it cannot be instantiated.(Error: DOMDocument* doc=new DOMDocument()).
     
    Then how, the class XercesDOMParser can return DOMDocument* type without the instantiation of DOMDocument class.
     
    XercesDOMParser* myParser=new XercesDOMParser();
     
    DOMDocument* doc=myParser->getDocument();
    You return a pointer to a (non-abstract) derived class object. A pointer to a derived class object can always be converted to a pointer to the base class.
     
    class A
    {
    public:
      virtual ~A(){}
      virtual void f() = 0;
    };
     
    class B; public A
    {
      virtual void f(){}
    };
     
    A* GetA()
    {
      return new B();
    }
     
    A* pA = GetA();
    pA->f(); // calls B::f()
     

    David Wilkinson | Visual C++ MVP
    • Marked as answer by Prabas08 Sunday, June 5, 2011 8:09 AM
    Saturday, June 4, 2011 12:29 PM

All replies

  • I have a big doubt on how to return pointer instance of abstract base class from its derived class.
     
    For example,
     
    in Xerces data object model, DOMDocument is an abstract class and hence it cannot be instantiated.(Error: DOMDocument* doc=new DOMDocument()).
     
    Then how, the class XercesDOMParser can return DOMDocument* type without the instantiation of DOMDocument class.
     
    XercesDOMParser* myParser=new XercesDOMParser();
     
    DOMDocument* doc=myParser->getDocument();
    You return a pointer to a (non-abstract) derived class object. A pointer to a derived class object can always be converted to a pointer to the base class.
     
    class A
    {
    public:
      virtual ~A(){}
      virtual void f() = 0;
    };
     
    class B; public A
    {
      virtual void f(){}
    };
     
    A* GetA()
    {
      return new B();
    }
     
    A* pA = GetA();
    pA->f(); // calls B::f()
     

    David Wilkinson | Visual C++ MVP
    • Marked as answer by Prabas08 Sunday, June 5, 2011 8:09 AM
    Saturday, June 4, 2011 12:29 PM
  • Dear Dave,

    This sounds good. Thanks a lot. Thanks to Aljod too...


    Sunday, June 5, 2011 8:11 AM