3
class Base {
public:
    int a;
    Base():a(0) {}
    virtual ~Base();
}
class Derived : public Base {
public:
    int b;
    Derived():b(0) {
        Base* pBase = static_cast<Base*>(this);
        pBase->Base();
    }
    ~Derived();
}

Is the call to the base class constructor necessary or does c++ do this automatically? e.g. Does C++ require you to initialize base class members from any derived class?

  • 1
    "*Does C++ require you to initialize base class members from any derived class?*" No, in fact it doesn't even allow you to. `Base::Base` initializes `Base`'s members, `Derived::Derived` invokes `Base::Base` then initializes `Derived`'s members. – ildjarn Aug 29 '12 at 00:05
  • Trying to compile this would let you see you can't call constructors like that. – chris Aug 29 '12 at 00:06
  • @chris I'm away from a compiler and i'm working in my head at the moment. Besides it clarifies for others who are googling later =) – Worryn Ashtrod Aug 29 '12 at 00:08
  • 1
    @WorrynAshtrod, http://ideone.com/ http://liveworkspace.org/ – chris Aug 29 '12 at 00:16

2 Answers2

9

The base class's constructor will automatically be called before the derived class's constructor is called.

You can explicitly specify which base constructor to call (if it has multiple) using initialization lists:

class Base {
  public:
    int a;
    Base():a(0) {}
    Base(int a):a(a) {}
};
class Derived {
  public:
    int b;
    Derived():Base(),b(0) {}
    Derived(int a):Base(a),b(0) {}
};
Andrew Rasmussen
  • 14,912
  • 10
  • 45
  • 81
  • Would you mind upvoting and accepting my answer if I've answered your question? Thanks :) – Andrew Rasmussen Aug 29 '12 at 07:23
  • 1
    Great answer!! I was searching for the syntax / order of member initializers of derived class and couldn't find a "good" question... luckily I came across this one. – Jess May 03 '13 at 01:13
1

Base class constructors are called automatically (and before derived class contructors). So you need not, and must not, try to call base constructors manually.

Jon
  • 428,835
  • 81
  • 738
  • 806