user2255962
user2255962

Reputation:

Call a Overloaded Function of Inherited Class from Base Class

#include<iostream>

class A {
    public:
        void init(){
                std::cout << "A" << std::endl;
        }
};
class B: public A {
    public:
    void init(){
            std::cout << "B" << std::endl;
    }
};
int main() {
        A *o = new B();

/*

Some codes here

*/
        o->init();
        return 0;
}

Result:
A

In the above program, the init called is of class A. How do I call the init function of class B?

edit: I need to call both the inits. I can't change the A and B class. And I have to make the object declaration like that in main.

Upvotes: 1

Views: 86

Answers (5)

leon
leon

Reputation: 21

since class B hides the definition of init() in its base-class, it will make the function sensitive to the type of any pointer or reference from which the function might be called. And as you mentioned A and B are prewritten class, you can instantiate a pointer to class B, or cast to a pointer to class B.

Upvotes: 0

Vahid Nateghi
Vahid Nateghi

Reputation: 584

You have some options here:

B *o = new B(); // in Main

or

(B *)o->init(); // in Main

or

virtual void init(){
                       std::cout << "A" << std::endl;
                   } // in Class A

Upvotes: 0

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

Make the init() function virtual in Class A.

class A {
    public:
        virtual void init(){
                std::cout << "A" << std::endl;
        }
};

The object o has two parts. The base part and the derived part. If you want B::init() to be called from o, then you will have to tell the compiler that it is a virtual function and it should look for the function overload in the derived class.

I suggest you go through the tutorial on this website to learn more about inheritance: http://www.learncpp.com/cpp-tutorial/113-order-of-construction-of-derived-classes/

Upvotes: 4

make init function virtual create a pointer of class A create an object of class B assign address of B object to pointer A now access init function of B

Upvotes: 0

deeiip
deeiip

Reputation: 3379

b = dynamic_cast<B*>(o);
if(b!=NULL)
   b->init();

this will call the function for object of type B.

Upvotes: 0

Related Questions