Dynamic casting problem

This code returns an error to me whenever I try to run this code. Can someone please help me.

struct m
{
    virtual int s( )
    { 
        return 1;
    }
};

struct n : public m
{
    int s( )
    { 
        return 2;
    }
};

int o( )
{
    n* p=new m;
    m* q=dynamic_cast<p>;
    return q->s( );
}
+3
source share
3 answers

These C ++ conversion operators should be used as

dynamic_cast<newType>(variable)

In your case

m* q = dynamic_cast<m*>(p); 

By the way, do you confuse the role mand n? n* p = new mis a syntax error because an instance of a base class cannot be implicitly converted to an instance of a derived class. In fact, the base → received by you is a situation when you really need it dynamic_cast, and not vice versa (casting is not required).

Also, consider providing meaningful names to objects.

+7
source

, , , !

, , , dynamic_cast ? , ,

m* q=dynamic_cast<m *>(p); 

, dynamic_cast - . . dynamic_cast, (, static_cast).

+2

: m n main. dynamic_cast. dynamic_cast<new type>(some var).

0

Source: https://habr.com/ru/post/1758262/


All Articles