How to use dynamic_cast on vector in C++

Hello Learners, today we are going to learn a very interesting and important topic that is dynamic_cast on vector using C++. It is one of the methods used for typecasting. The word type casting is nothing but, converting an expression of a given type into another type is known as typecasting.

dynamic_cast on vector in C++

Before going to code we need to be clear with the syntax of dynamic_cast and working of it. And dynamic_cast only works when we have at least one virtual function in the base class. That is dynamic_cast works whenever there is a polymorphism.

Syntax:

    dynamic_cast<newtype>(expression)

Code:1)

#include<iostream> 
using namespace std; 
class base
{ 

    public:
     void sample_function() 
    {
        cout<<"base class called "<<endl;
    } 
    
}; 
class derived : public base 
{ 
    public:
    
    void sample_function()
    {
        cout<<"derived class called"<<endl;
    }
}; 
  
int main() 
{ 
    base *b = new derived; 
    base *c=  new base;
    c->sample_function();
    derived *d = dynamic_cast<derived*>(b); 
    if(d==0) 
    {
        cout<<"cannot cast B* to D*";
    }
    else
    {
        cout<<"dynamic cast working sucessfully : "<<endl;
        d->sample_function();
    }
    getchar(); 
    return 0; 
}

The above code will not work it will show you an error that is:

error: cannot dynamic_cast ‘b’ (of type ‘class base*’) to type ‘class derived*’ (source type is not polymorphic)
— It means in base class we haven’t declared virtual keyword. Now try to include the virtual keyword in base class function and let’s check the output.

Code:2)

#include<iostream> 
using namespace std; 
class base
{ 

    public:
     void virtual sample_function() 
    {
        cout<<"base class called "<<endl;
    } 
    
}; 
class derived : public base 
{ 
    public:
    
    void sample_function()
    {
        cout<<"derived class called"<<endl;
    }
}; 
  
int main() 
{ 
    base *b = new derived; 
    base *c=  new base;
    c->sample_function();
    derived *d = dynamic_cast<derived*>(b); 
    if(d==0) 
    {
        cout<<"cannot cast B* to D*";
    }
    else
    {
        cout<<"dynamic cast working sucessfully : "<<endl;
        d->sample_function();
    }
    getchar(); 
    return 0; 
}

Output:

base class called 
dynamic cast working sucessfully : 
derived class called

Also, read: Getting the Current Directory in C++

Leave a Reply

Your email address will not be published. Required fields are marked *