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;
}
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,
Output:
Base Class fun.
Now access derived class member using the typecasting but is not recommended,
Output:
Child Class fun.
need an explanation for this answer? contact us directly to get an explanation for this answer