| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"" |
| Date: |
29 Mar 2006 08:40:54 AM |
| Object: |
Order of constructor execution? |
Hi. I have base class Base and derived class Derived. My derived
class constructor is dependent upon attributes set in the base class
constructor. Is this okay? Does ANSI C++ guarantee that a base class
constructor will complete before the derived class contructor executes?
Thanks!
Ken
.
|
|
| User: "Bob Hairgrove" |
|
| Title: Re: Order of constructor execution? |
29 Mar 2006 08:51:40 AM |
|
|
On 29 Mar 2006 06:40:54 -0800, wrote:
Does ANSI C++ guarantee that a base class
constructor will complete before the derived class contructor executes?
For regular inheritance (public, protected or private) the answer is
yes. For virtual inheritance, the rules are a little different, but in
most cases also yes. The base class constructor in a virtual
inheritance hierarchy is invoked by the most-derived class
constructor, whereas otherwise it is invoked by the constructor of the
next class in its hierarchy.
This should also be covered in the FAQ link that Phlip posted.
--
Bob Hairgrove
NoSpamPlease@Home.com
.
|
|
|
|
| User: "Michael Rasmussen" |
|
| Title: Re: Order of constructor execution? |
29 Mar 2006 05:00:42 PM |
|
|
On Wed, 29 Mar 2006 06:40:54 -0800, kk_oop wrote:
Hi. I have base class Base and derived class Derived. My derived class
constructor is dependent upon attributes set in the base class
constructor. Is this okay? Does ANSI C++ guarantee that a base class
constructor will complete before the derived class contructor executes?
This small test should explain all:
#include <iostream>
using namespace std;
class foo_base {
protected:
string test;
public:
foo_base() : test ("assigned") {};
~foo_base() {};
};
class bar_derived : public foo_base
{
public:
bar_derived() {};
~bar_derived() {};
string getTest() { return test; };
};
int main(void)
{
bar_derived *bar = new bar_derived();
cout << bar->getTest() << endl;
exit (EXIT_SUCCESS);
}
--
Hilsen/Regards
Michael Rasmussen
http://keyserver.veridis.com:11371/pks/lookup?op=get&search=0xE3E80917
.
|
|
|
|
| User: "Phlip" |
|
| Title: Re: Order of constructor execution? |
29 Mar 2006 08:45:39 AM |
|
|
kk_oop wrote:
Hi. I have base class Base and derived class Derived. My derived
class constructor is dependent upon attributes set in the base class
constructor. Is this okay? Does ANSI C++ guarantee that a base class
constructor will complete before the derived class contructor executes?
Yes. Just don't do it the other way around, where the base class depends on
derived class values.
This FAQ entry explains one way to do that which the language prevents:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.5
There are others.
--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
.
|
|
|
|

|
Related Articles |
|
|