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
  • 67,195
  • 30
  • 170
  • 212
user2553917
  • 61
  • 1
  • 1
  • 2

2 Answers2

6

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,333
  • 3
  • 39
  • 65
6

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
  • 380,411
  • 33
  • 383
  • 585