Friday, February 8, 2013

Call derived class method from base class reference

Reference: here

What you want is polymorphism, and to enable it for a function you need to make it virtual:

class Material 
{ 
public: 
    virtual void foo() // Note virtual keyword!
    { 
        cout << "Class Material"; 
    } 
}; 

class Unusual_Material : public Material 
{ 
public: 
    void foo() // Will override foo() in the base class
    { 
        cout << "Class Unusual_Material"; 
    } 
}; 
 
Also, polymorphism only works for references and pointers:

int main()  
{  
    Unusual_Material unusualMaterial;
    Material& strange = unusualMaterial;
    strange.foo();  
    return 0; 
}

/* OR */

int main()  
{  
    Unusual_Material unusualMaterial;
    Material* strange = &unusualMaterial;
    strange->foo();  
    return 0; 
}
 
***********************************************************************************************
 
#include <stdio.h>
using namespace std;

class A
{
    public :
    virtual int get()
    {
        printf("in A\n");
        return 0;
    }
};

class B:public A
{
    public:
    int get()
    {
        printf("in B\n");
        return 0;
    }
};

int main()
{
    A a; 
    B b;
    
    a.get();  //in A
    b.get();  //in B
   
    A* aptr;
    aptr = &b;
    aptr->get(); // with virtual get()- o/p: in B
                 // without virtual get()- o/p: in A
 return 0;
} 
 

No comments:

Post a Comment