Pointers to Derived Class Objects


#include <iostream.h>
/*----------------------Class Interfaces-------------------------*/
class A
{
        int a1;                    // private data member
    public :
        int a2;                    // public data member

        void set(int);
        void display();
};
class B : public A
{
        int a3;                    // private data member
    public :
        int a4;                    // public data member

        void set(int);       // overriding functions
        void display();
};
/*----------------------Class Implementations---------------------*/
// member function definitions for class A
void A::set(int x)
{
    a1 = x;
}
void A::display()
{
    cout << "a1 = " << a1 << "\n";
    cout << "a2 = " << a2 << "\n";
}
// member function definitions for class B
void B::set(int x)
{
    a3 = x;
}
void B::display()
{
    A::display();
    cout << "a3 = " << a3 << "\n";
    cout << "a4 = " << a4 << "\n";
}
/*----------------------Class definitions ends here---------------*/
void main(void)
{
    A *base, obj1;
    base = &obj1;
    base->set(1);
    base->a2 = 2;
    cout << "Base class data members : \n";
    base->display();
    B obj2;                    // Derived class object
    base = &obj2;
    base->set(10);
    base->a2 = 20;
    cout << "Base class data members (through subsumption) : \n";
    base->display();
    B *derived;
    derived = &obj2;
    derived->set(30);
    derived->a4 = 40;
    cout << "Derived class data members : \n";
    derived->display();
}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|