CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2010
    Posts
    1

    Inheritance of base class constructor?

    Hi,

    I have a doubt regarding inheritance of base class constructor by inherited class.

    I was recently going through some C++ online tutorial when I came across this piece of code:

    Code:
    #include <iostream>
    class Foo
    {
            public:
            Foo() { std::cout << "Foo's constructor" << std::endl; }
    };
    class Bar : public Foo
    {
            public:
            Bar() { std::cout << "Bar's constructor" << std::endl; }
    };
    
    int main()
    {
            // a lovely elephant ;)
            Bar bar;
    }
    I will quote the exact text present in the site from where I took the above code :

    Code:
    The object bar is constructed in two stages: first, the Foo constructor is invoked and then the Bar constructor is invoked. The output of the above program will be to indicate that Foo's constructor is called first, followed by Bar's constructor.

    Now, my question is:

    Will the constructor Foo() be called when an object of class Bar is declared?


    This is the site from where I got the above code:
    Initialization Lists in C++


    Now according to the site, the constructor Foo() will be called. But as per my knowledge, this is not true since base class constructors are not inherited. But I want to confirm this.

    Regards,

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Inheritance of base class constructor?

    It will be called, but it is not, strictly speaking, inherited.

    If the constructor were inherited, then it would be possible to call only Foo's constructor somehow. It isn't; the Foo constructor can only be called as part of the Bar constructor call from Bar's point of view.

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Inheritance of base class constructor?

    It is true that the base class constructors are not inherited. However, there is a base class subobject, and a base class constructor must be invoked to construct that. Since you did not specify the base class constructor to use in the initialisation list, the default constructor of the base class is invoked.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured