0

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
1
  • 2
    Did you mean to case bptr, and not base (which is the type)? Commented Jul 31, 2018 at 7:46

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.