2
// Use multiple inheritance. We want 
// both a string and an Object:
class MyString: public string, public Object {
public:
  ~MyString() {
    cout << "deleting string: " << *this << endl;
  }
  MyString(string s) : string(s) {}
};

For the above code, I do not understand what string(s) mean? There is no variable called string in fact, but why it can work?

Tom Xue
  • 3,169
  • 7
  • 40
  • 77
  • possible duplicate of [What is this weird colon-member syntax in the constructor?](http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor) – Alok Save Mar 13 '13 at 14:51
  • It's not a duplicate. The question you linked to is about member initialization, in this case, the base-class-constructor is called. As the OP mentioned, there is no member called string. – JSQuareD Mar 13 '13 at 15:04
  • 1
    Just to say, you probably don't want to derive from `string`. – Peter Wood Mar 13 '13 at 15:11

4 Answers4

3

Usually, when constructing a derived class, the default base-constructor (if it exists) will be called. If you want to explicitly call a different base-constructor for a certain derived-constructor, you can do this using the initializer list.

In this case, when constructing MyString, the string-constructor which takes a string as its only argument (the copy constructor), will be called with s as the argument.

JSQuareD
  • 4,641
  • 2
  • 18
  • 27
  • I seem to vaguely recall that it's a C++11 feature. Right or not? Is there a specific term for it (besides "initializer list" which usually refers to initializing fields)? – Igor Skochinsky Mar 13 '13 at 16:18
  • As far as I'm aware, it's the only way to call a base-constructor, and it's been around for quite some time. I think what you're remembering is the fact that all member initializations now have to be done in constructors (initializer list or body, but not at declaration, as in `int member=3`). – JSQuareD Mar 13 '13 at 16:20
2

The string(s) is constructing the parent class instance of MyString with s.

Note that MyString inherits from string, this is what that use of string refers to.

This is known as an "initializer list".

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
1

It initialises the parent subobject of type string. In effect, it specifies which parent constructor to call for the string parent.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

MyString derives from string. The syntax you refer to, string(s), calls the base class constructor with s as the sole argument.

NPE
  • 486,780
  • 108
  • 951
  • 1,012