-
August 5th, 2010, 12:35 PM
#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,
-
August 5th, 2010, 12:37 PM
#2
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.
-
August 5th, 2010, 12:40 PM
#3
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|