FYI, I was playing with inheritance yesterday to test how/whether the
child constructor/destructor would call those of the parent. Below is my
test code. Obviously I found out what people have been telling you: That
the child's constructor calls the parent's default constructor
automatically unless otherwise specified in the initializer list.
The attempt to call the parent's default constructor *outside* the
initializer list and actually in the body of the child's constructor bit
me, too (i.e., it did not initialize the child's data members). You said
that "did not work".
Suzanne
-------------------------------------------------------------------------------
//
http://www.cs.unc.edu/~vogel/playpen...nheritance.cpp
/************************************************** ****************************
* File: Inheritance.cpp
* Purpose: Test inheritance, with use of parent's constructor and
destructor.
************************************************** ****************************/
#ifndef _STD_USING
#define _STD_USING // Must be #define'd in order to include stddef.h.
#endif // _STD_USING
#include <iostream>
class Parent {
public:
static const int filler = 99;
int* ints;
int n;
int magicNumber;
public:
Parent(const int n=10) {
std::cout << "Parent constructor #1\n";
this->n = n;
this->ints = new int[n];
for (int i=0; i<this->n; i++) {
this->ints[i] = Parent::filler;
}
this->magicNumber = -1;
}
Parent(const int n, const int m) {
std::cout << "Parent constructor #2\n";
this->n = n;
this->ints = new int[n];
for (int i=0; i<this->n; i++) {
this->ints[i] = Parent::filler;
}
this->magicNumber = m;
}
~Parent() {
std::cout << "Parent destructor\n";
delete[] this->ints;
}
};
class Child : public Parent {
public:
Child(const int n=10) {//: Parent(n) { // Parent default
constructor called automatically!
std::cout << "Child constructor #1\n";
}
Child(const int n, const int m) : Parent(n,m) { // Call parent
constructor!!!
std::cout << "Child constructor #2\n";
//Parent::Parent(n,m); // This is *not* valid!
}
~Child() { // Parent destructor is called automatically!
std::cout << "Child destructor\n";
}
};
int main(int argc, char** argv) {
// 1. Test whether parent destructor is called automatically (it is).
Child* c0 = new Child();
int* a = c0->ints;
delete c0;
if (a[0]==Parent::filler) {
std::cout << "ERROR: Child not deleted!\n"; // Not printed out
(Good!)
}
std::cout << a[0] << "\n"; // Senseless number (Good!)
//-------------------------------------------------------------------------
// 2. Test whether parent constructor is called automatically (it is),
// and how. Turns out the *default* parent constructor is called
automatically,
// unless the child calls another constructor *before* the block {}.
std::cout <<
"//--------------------------------------------------------\n";
Child* c1 = new Child(99, 10);
int* b = c1->ints;
std::cout << "magic number: " << c1->magicNumber << "\n";
std::cout << b[0] << "\n";
delete c1;
return 1;
}