0

I have a problem calling the default constructor from other in c++. In Java was something like this:

class Book {
  static private int i;
  private String s;

  public Book() {
    i++;
  }

  public Book(String s) {
    this();
    this.s = s;
  }
}
Ben S
  • 68,394
  • 30
  • 171
  • 212
user2553917
  • 61
  • 1
  • 1
  • 2

2 Answers2

9

In C++ we have delegating constructors. There are two things to know about it:

  • They are available only since C++11, and not all compilers already implement them.

  • The correct syntax is to use the constructor's initializer list:

    Book(std::string s) : Book() { ... }

syam
  • 14,701
  • 3
  • 41
  • 65
7

If you have a compiler capable of delegating constructor, just call the default constructor in the initializer list:

class Book
{
public:
    Book()
    { ... }

    Book(const std::string& s)
    : Book()
    { ... }
};

Else you can make a function for common initialization and call it from all constructors:

class Book
{
public:
    Book()
    { construct(); }

    Book(const std::string& s)
    {
        construct();
        // Other stuff
    }

private:
    void construct()
    { ... }
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621