Thread: Dynamic Casting Question

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    103

    Dynamic Casting Question

    Hi All

    I have a question on dyanamic casting.

    Below is the code:

    Code:
    #include<iostream>
    using namespace std;
    
    class base
    {
    public:
    
    	virtual int get()
    	{
    		cout<<"Inside base";
    		return 1;
    	}
    
    };
    
    
    class derived : public base
    {
    public:
    
    	int get()
    	{
    		cout<<"Inside derived";
    		return 1;
    	}
    
    };
    
    
    int main()
    {
    	derived *b =  new base();
    	b->get();
    	getchar();
      return 0;
    }
    This code is giving compile time error that:

    cannot convert from 'class base *' to 'class derived *'
    I want to understand why? What I was thinking that since derived class is pointing to base class, which mean that we are going from specialized class to generalized one, so that should be legal. In other words, upcasting.

    Can anybody help to understand this?

    Thanks
    Nickman

  2. #2
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    You have it backwards. Derived* asserts that what you refer to is of type Derived. An instance of Base is not a Derived, but an instance of Derived is a Base. This
    Code:
    Base *b = new Derived();
    Creates an instance of Derived but refers to it using only the interface provided by Base. What you did, in contrast, is go from a less specialized class to a more specialized one. You created a Base and then referred to it as a Derived -- but it's not a Derived, it's just a Base.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Casting Problem
    By nickman in forum C++ Programming
    Replies: 2
    Last Post: 10-10-2013, 04:57 PM
  2. casting question
    By kerrymaid in forum C Programming
    Replies: 5
    Last Post: 10-22-2011, 07:35 AM
  3. Question on casting 0
    By laertius in forum C Programming
    Replies: 2
    Last Post: 11-09-2008, 12:15 PM
  4. question about casting
    By movl0x1 in forum C Programming
    Replies: 8
    Last Post: 07-09-2007, 09:51 PM
  5. Casting Question (I think)
    By fayte in forum C Programming
    Replies: 6
    Last Post: 03-08-2006, 05:31 PM