Could you please help me how to call the derived class non virtual function using Static or Dynamci cast.
I want to call derive call function "test" by using static or dynamic cast only.
#include<iostream>
using namespace std;
class base
{
public:
virtual void call()
{
cout<<"I am base"<<endl;
}
/*void test()
{
cout<<"I am test"<<endl;
}*/
};
class derive:public base
{
public:
void call()
{
cout<<"I am derive"<<endl;
}
void test()
{
cout<<"I am derived test"<<endl;
}
};
int main()
{
derive d;
base *bptr = &d;
bptr->call();
derive* dptr = dynamic_cast<derive *>(base);
dptr->test();
return 0;
}
While compiling, I am getting below error:
main.cpp: In function 'int main()':
main.cpp:34:47: error: expected primary-expression before ')' token
derive* dptr = dynamic_cast<derive *>(base);
^
Could you please tell me where I have mistaken.
haccks
107k28 gold badges181 silver badges274 bronze badges
asked Jul 31, 2018 at 7:43
Anand Ganesan
411 silver badge4 bronze badges
-
2Did you mean to case bptr, and not base (which is the type)?JLev– JLev2018年07月31日 07:46:14 +00:00Commented Jul 31, 2018 at 7:46
1 Answer 1
Remember dynamic_cast< Type* >(ptr)
Change
derive* dptr = dynamic_cast<derive*>(base);
to
derive* dptr = dynamic_cast<derive*>(bptr);
Which gives as result :
I am derive
I am derived test
Because base is a type (if you use a uppercase on the first letter for all your type/class you would have noticed that you were using a type and not a variable).
answered Jul 31, 2018 at 7:48
Hearner
2,7073 gold badges19 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-cpp