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;
  }
}
6
  • 5
    In C++11 you can use delegating constructors Commented Jul 5, 2013 at 13:50
  • That code isn't valid C++ ( I think you already know that ). What's the question? Commented Jul 5, 2013 at 13:51
  • This is a java code i need to know how will be this code in c++ Commented Jul 5, 2013 at 13:53
  • Possible duplicate of: stackoverflow.com/questions/17454823/… Commented Jul 5, 2013 at 13:53
  • Time to read a good book on C++. stackoverflow.com/questions/388242/… Commented Jul 5, 2013 at 13:54

2 Answers 2

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() { ... }

Sign up to request clarification or add additional context in comments.

Comments

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()
    { ... }
};

1 Comment

Strange in c# it Works fine, but in c++ not... well i will create a function that will hold the code i need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.