Java FAQ:サブクラスでは必ずコンストラクタを記述しないとダメ

Java FAQ:S010 Q-02

なんでそういう仕様なんだっけ?C++ も同じかな?

class C2008041301 {
    C2008041301() {
        System.out.println("C2008041301");
    }
}

class C2008041302 extends C2008041301 {
    C2008041302() {
        System.out.println("C2008041302");
    }
}

public class C2008041300 {
    public static void main(String[] args) {
        new C2008041302();
    }
}

で、

C2008041301
C2008041302

デフォルトコンストラクタは継承されるようだ

class C2008041311 {
    C2008041311(String str) {
        System.out.println("C2008041311: " + str);
    }
}

class C2008041312 extends C2008041311 {
    C2008041312(String str) {
        super(str);
        System.out.println("C2008041312: " + str);
    }
}

public class C2008041310 {
    public static void main(String[] args) {
        new C2008041312("foo");
    }
}

で、

C2008041311: foo
C2008041312: foo

「super(str);」がないとコンパイルエラー


C++だと?

#include <iostream>

using namespace std;

class Foo
{
public:
  Foo() {
      cout << "Foo()" << endl;
  }
  Foo(string str) {
      cout << "Foo(): " << str << endl;
  }
};

class Bar : public Foo
{
public:
  Bar(string str) {
      cout << "Bar(): " << str << endl;
  }
};

int main()
{
  Bar("hoge");

  return 0;
}

で、

Foo()
Bar(): hoge
  • class の最後に「;」いるんだった〜
  • コンストラクタって pulic じゃないのか〜
  • デフォルトコンストラクタがないとエラーになった
#include <iostream>

using namespace std;

class Foo
{
public:
  Foo(string str) {
      cout << "Foo(): " << str << endl;
  }
};

class Bar : public Foo
{
public:
  Bar(string str) : Foo(str) {
      cout << "Bar(): " << str << endl;
  }
};

int main()
{
  Bar("hoge");

  return 0;
}

で、

Foo(): hoge
Bar(): hoge
#include <iostream>

using namespace std;

class Foo
{
public:
  Foo() {
    cout << "Foo()" << endl;
  }
};

class Bar : public Foo
{
public:
  Bar() {
    cout << "Bar()" << endl;
  }
};

int main()
{
  Bar();

  return 0;
}

で、

Foo()
Bar()