+ Reply to Thread
Results 1 to 2 of 2

Thread: Why does my code always calls base class method?

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    28

    Why does my code always calls base class method?

    Below code always calls base class method instead I expect it to make a call to derive class method:

    Code:
    class CBase
    {
    public:
    	virtual int GetData() const
    	{
    		return 42 ;
    	}
    } ;
    
    class CDerive : public CBase
    {
    public:
    	virtual int GetData()
    	{
    		return 42 ;
    	}
    } ;
    
    void UseDerive()
    {
    	CBase *pBase = new CDerive() ;
    
    	int nData = pBase->GetData() ;
    }
    Am I missing something?

    Please help.

  2. #2
    It seems that you have mistakenly wrote "const" in base class or forgot to write the same in derive class.

    Following works fine for me:

    Code:
    class CBase
    {
    public:
    	virtual int GetData() const
    	{
    		return 42 ;
    	}
    } ;
    
    class CDerive : public CBase
    {
    public:
    	virtual int GetData() const //note the 'const' here
    	{
    		return 42 ;
    	}
    } ;
    
    void UseDerive()
    {
    	CBase *pBase = new CDerive() ;
    
    	int nData = pBase->GetData() ;
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts