Order of constructor execution?

K

kk_oop

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
 
P

Phlip

kk_oop said:
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.
 
B

Bob Hairgrove

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.
 
M

Michael Rasmussen

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);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top