Saturday, February 2, 2013

Constructor with Inheritance


Constructor in derived class:
·        The base class contain constructor with one or more parameter, then it is mandatory for the derived class to have constructor and pass the parameter to the base class constructor.
·        In the case of inheritance first base class constructor is called then derived class constructer is called. In the case of destructor first derived class destructor is called then base class destructor is called.

class Base
{
            public:
            Base()
            {
                        cout<<”Base class default constructor”;
            }
            Base(int a)
            {
                        cout<<”Base class parameterized constructer”;
            }
            ~Base()
            {
                        cout<<”Base class destructer”;
            }
};

class Derived:public Base
{
            public:
            Derived()
            {
                        cout<<”Derived class default constructor”;
            }
            Derived(int b):Base(b)
            {
                        cout<<”Derived class parameterized constructor”;
            }
            ~Derived()
            {
                        cout<<”Derived class destructor”;
            }
};
void main()
{
            clrscr();
            {
                        Derived obj(10); // parameterized
            }
            {
                        Derived obj1; //Default
            }
}

0 comments:

Post a Comment

Powered by Blogger.