-2

I have three classes: I have access to the only base class pointer, but this pointer is actually a derived class object. I want to use this base pointer to call the base class virtual function.

    class A
    {
        public:
        virtual void print() = 0;
    };

    class B: public A
    {
       public:
        virtual void print() override { cout <<"I am B\n"; }
    };

    class C: public B
    {
        public:
        virtual void print() override { cout <<"I am C\n"; }
    };

    int main()
    {
        cout<<"Hello World\n";

        A *a = new C();
        a->print(); // prints "I am C"

        //use pointer 'a' to print "I am B"

        return 0;
   }
Satyam Raikar
  • 465
  • 6
  • 20

1 Answers1

-1

Posted this question, while reading a book, after two pages found this!

class A
{
    public:
    virtual void print() = 0;
};

class B: public A
{
    public:
    virtual void print() override { cout <<"I am B\n"; }
};

class C: public B
{
    public:
    virtual void print() override { cout <<"I am C\n"; }
};

int main()
{
    cout<<"Hello World\n";

    A *a = new C();
    a->print();


    B *b = dynamic_cast<B*>(a);
    b->B::print();

    return 0;
}
Satyam Raikar
  • 465
  • 6
  • 20
  • 1
    I believe your question is too trivial for self answer, and is likely of no interest to others. It is also a duplicate. – SergeyA May 11 '18 at 05:13
  • In most answers base class method was called in the derived class method using something like Base::method(). There were no answers that suggested downcasting. In my code, I was not allowed to modify derived class definition. The whole point of this question was, how to downcast and use a base class pointer to call a virtual function. I didn't find this answer anywhere in stack.. – Satyam Raikar May 11 '18 at 05:53
  • There is an answer there just exactly for that. – SergeyA May 11 '18 at 05:59