Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7888013
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T05:43:42+00:00 2026-06-03T05:43:42+00:00

This program runs without any exception. Can you please explain why the dynamic cast

  • 0

This program runs without any exception. Can you please explain why the dynamic cast and static casts are successful? And how C++ manages to resolve the required virtual function?

class Shape 
    {
    private :
        string helperFunction();

    public : 
        virtual void draw() = 0;
        virtual void type();
    };

void Shape::type()
    {
    cout << "Shape Type";
    }

// ----------------------------------------------------------------------------

class Circle : public Shape
    {
    private: 
    string circlething;

    public :
        virtual void draw();
        virtual void type();
        void CircleFunction();
    };

void Circle::draw()
    {
    cout <<"Circle Draw" << endl;
    }

void Circle::type()
    {
    cout <<"Circle Type" << endl;
    }

void Circle::CircleFunction()
    {
    circlething = "Circle Thing";
    cout << circlething;
    cout << "Circle Function" << endl;
    }


class Square : public Shape
    {
    private :
        string  squarething;
    public :
        virtual void draw();
        virtual void type();
        void SquareFunction();
    };

void Square::draw()
    {
    cout <<"Square Draw" << endl;
    }

void Square::type()
    {
    cout <<"Square Type" << endl;
    }

void Square::SquareFunction()
    {
    squarething = "Square Thing";
    cout << squarething;
    cout << "Square Function" << endl;
    }
// ----------------------------------------------------------------------------


int _tmain(int argc, _TCHAR* argv[])
    {
    vector<Shape *> shapes;
    Circle circle;
    Square square;
    shapes.push_back(&circle);
    shapes.push_back(&square);

    vector<Shape *>::const_iterator i;

    for (i = shapes.begin(); i < shapes.end(); ++i)
        {

        cout << "\n*** Simple Type ***\n" << endl;
        (*i)->type();
        (*i)->draw();

        cout << "---Static Cast Circle--" << endl;
        Circle* circle = static_cast<Circle*>(*i);
        circle->type();
        circle->draw();
        circle->CircleFunction();

        cout << "---Static Cast Square--" << endl;
        Square* square = static_cast<Square*>(*i);
        square->type();
        square->draw();
        square->SquareFunction();

        cout << "---Static Cast Circle to Shape --" << endl;
        Shape* shape1 = static_cast<Shape*> (circle);
        shape1->type();
        shape1->draw();

        cout << "--- Dynamic Cast Circle to Shape --" << endl;
        Shape* shape2 = dynamic_cast<Shape*> (circle);
        shape2->type();
        shape2->draw();

        cout << "--- Static Cast Square to Shape --" << endl;
        Shape* shape3 = static_cast<Shape*> (square);
        shape3->type();
        shape3->draw();

        cout << "--- Dynamic Cast Square to Shape --" << endl;
        Shape* shape4 = dynamic_cast<Shape*> (square);
        shape4->type();
        shape4->draw();

        }
    int x;
    cin >> x;
    return 0;
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T05:43:43+00:00Added an answer on June 3, 2026 at 5:43 am

    Let’s start with why it isn’t throwing any exceptions, since it’s pretty simple: dynamic_cast throws an exception when you try to cast a reference type, and it fails. When you use dynamic_cast on pointers, it will return a pointer if it succeeds, or a null pointer if it fails.

    As for why you’ve never getting a failed cast, all your dynamic_cast are up the hierarchy, to produce a Shape *. Since all the objects in question are derived from Shape, this will always succeed — and in fact, that conversion can be done implicitly.

    To demonstrate what dynamic_cast is really intended to do, let’s write some slightly different code:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    class Shape {
    public : 
        virtual void draw() = 0;
    };
    
    class Circle : public Shape
    {
    public :
        virtual void draw() { cout << "Circle Draw\n"; }
        void circlefunc() { cout << "circle func\n"; }
    };
    
    class Square : public Shape
    {
    public :
        virtual void draw() { cout << "Square Draw\n"; }
        void squarefunc() { cout << "Square Func\n"; }
    };
    
    int main() {
        vector<Shape *> shapes;
        Circle circle;
        Square square;
        shapes.push_back(&circle); // implicit conversion from Circle * to Shape *
        shapes.push_back(&square); // implicit conversion from Square * to Shape *
    
        Circle *c;
        Square *s;
        for (int i=0; i<shapes.size(); i++) {
            shapes[i]->draw(); // draw polymorphically
            if (c = dynamic_cast<Circle *>(shapes[i])) // try to cast to Circle *
                c->circlefunc();               // if it worked, invoke circlefunc
            else if (s = dynamic_cast<Square *>(shapes[i])) // likewise for square
                s->squarefunc();
        }
        return 0;
    }
    

    This time we’re using the dynamic_cast to get from Shape * to Square * or Circle *. This will succeed if and only if the dynamic type of the pointee object is that type. Otherwise it’ll produce a null pointer. If and only if we get a non-null pointer, we invoke the member function for that specific type.

    To summarize: When you have a pointer/reference to a derived object, you can convert to a pointer/reference to the base class implicitly. You don’t need dynamic_cast (or any explicit cast at all) because this is always safe.

    When you convert from pointer/reference to base to get a pointer/reference to derived, then you normally want to use a dynamic_cast. This will succeed/fail based on whether the actual type of the pointee object (i.e., the dynamic type) is the desired target (or a base of it) or not. In this case, failure is signaled differently depending on whether you’re working with pointers or references. For a reference, failure will throw an exception. For a pointer, failure will produce a null pointer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This program in C runs and compiles well : #ifdef HAVE_CONFIG_H #include <config.h> #endif
So I have a program which runs. This is part of the code: FileName
I have a program which does a system call: latex somefile.latex This runs ok,
This program is meant to generate a dynamic array, however it gives an access
This popup comes up as soon as the app is started: The program can't
I just realised that this program compiles and runs (gcc version 4.4.5 / Ubuntu):
//This program is taken from http://www.learncpp.com/cpp-tutorial/114-constructors-and-initialization-of-derived-classes/ #include <iostream> using namespace std; class A {
This program I use has it's own variables to set when you run it,
This program stores pairs in a map, counting the number of times a word
This program reads emails (really just a .txt file structured like an email) and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.