Need of Explicit Constructor Call in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sbvishal
    New Member
    • Sep 2007
    • 6

    Need of Explicit Constructor Call in C++

    [code=cpp]class Base
    { public:
    Base(){}
    /*Base(int x)
    {
    int a=x;
    //int b=y;
    cout<<"b="<<a<< endl;
    //cout<<"y="<<b<< endl;
    }*/
    };

    class der: public Base
    { public:
    der(int x)//:Base(x)
    {
    int a=x;cout<<"x="< <a<<endl;
    }
    };

    void main()
    {
    der d(1);
    getch();

    }
    [/code]
    In above program if we dont use the default constructor then we have to use explicit calling of constructor.
    Why it is required......
    Last edited by sicarie; Sep 25 '07, 02:04 PM. Reason: Code tags
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #2
    Originally posted by sbvishal
    [code=cpp]class Base
    { public:
    Base(){}
    /*Base(int x)
    {
    int a=x;
    //int b=y;
    cout<<"b="<<a<< endl;
    //cout<<"y="<<b<< endl;
    }*/
    };

    class der: public Base
    { public:
    der(int x)//:Base(x)
    {
    int a=x;cout<<"x="< <a<<endl;
    }
    };

    void main()
    {
    der d(1);
    getch();

    }
    [/code]
    In above program if we dont use the default constructor then we have to use explicit calling of constructor.
    Why it is required......
    Because base class must be initialized before derived one initialized.

    Kind regards,
    Dmjpro.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Adding to this, the derived class object is really a compound object. That is, there is a base object inside the derived object. As a derived class, there is no knowledge as to how to initialize that inner base object, yet it must be initialized. Therefore, the derived class must call the constructor of it's immediate base class.

      You will find that as the hierarchy deepens, each derived class constructor must have enough arguments to call the immediate base class constructor.

      Comment

      Working...