Monday, February 15, 2016

CONSTRUCTORS IN DERIVED CLASSES

CONSTRUCTORS IN DERIVED CLASSES

     A constructor plays a vital role in initializing an object. An important note, while using constructors during inheritance, is that, as long as a base class constructor does not take any arguments, the derived class need not have a constructor function. However, if a base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructor. Remember, while applying inheritance, we usually create objects using derived class. Thus, it makes sense for the derived class to pass arguments to the base class constructor. When both the derived and base class contains constructors, the base constructor is executed first and then the constructor in the derived class is executed.

Example:
// program to show how constructors are invoked in derived class
#include <iostream.h>
class alpha
(
    private: 
        int x; 
    public: 
        alpha(int i)
        {
            x = i;
            cout << "\n alpha initialized \n";
        }
        void show_x()
        {
            cout << "\n x = "<<x;
        }
);
class beta
(
    private: 
        float y; 
    public: 
        beta(float j)
        {
            y = j;
            cout << "\n beta initialized \n";
        }
        void show_y()
        {
            cout << "\n y = "<<y;
        }
);
class gamma : public beta, public alpha
(
    private: 
        int n,m; 
    public: 
        gamma(int a, float b, int c, int d):: alpha(a), beta(b)
        {
            m = c;
            n = d;
            cout << "\n gamma initialized \n";
        }
        void show_mn()
        {
            cout << "\n m = "<<m;
            cout << "\n n = "<<n;
        }
);

void main()
{
    gamma g(5, 7.65, 30, 100);
    cout << "\n";
    g.show_x();
    g.show_y();
    g.show_mn();
}
Output:
beta initialized

alpha initialized

gamma initialized


x = 5
y = 7.65
m = 30
n = 100

No comments:

Post a Comment