Q:

How to access derived class function from the base class object without using virtual function in c++?

0

How to access derived class function from the base class object without using virtual function?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

Using the typecasting we can call derive class object but not recommended because you have a virtual keyword. Let see an example program for the same,

#include<iostream>
using namespace std;
class A
{
public:
    A() {};
    ~A() {};
    void fun()
    {
        cout << "Base Class fun"<<endl;
    }
};
class B: public A
{
public:
    B() {};
    ~B() {};
    void fun()
    {
        cout << "Child Class fun"<<endl;
    }
};
int main()
{
    B bObj;
    A *aObj = &bObj;
    aObj->fun();
    return 0;
}

Output:

Base Class fun.

Now access derived class member using the typecasting but is not recommended,

#include<iostream>
using namespace std;
//Base class
class A
{
public:
    A() {};
    ~A() {};
    void fun()
    {
        cout << "Base Class fun"<<endl;
    }
};
//Child class
class B: public A
{
public:
    B() {};
    ~B() {};
    void fun()
    {
        cout << "Child Class fun"<<endl;
    }
};
int main()
{
    B bObj;
    A *aObj = &bObj;
    
    //Now Access child class but not recommended
    static_cast<B*>(aObj)->fun();
    
    return 0;
}

Output:

Child Class fun.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now