class Word              /* File: public-member-init.cpp */
{
  public:
    int frequency;
    const char* str;
};

int main() { Word movie = {1, "Titanic"}; }

This is the public member init

It can not work for private data members

Screenshot 2024-02-25 at 00.20.32.png

Word movie; // Default constructor
Word director = "J. Cameron"; // Implicit conversion constructor
Word sci_fi("Avatar"); // Explicit conversion constructor
Word drama {"Titanic"}; // C++11: Explicit conversion constructor
Word* p = new Word("action", 1); // General constructor

There are four types of constructor

Default constructor

class Word              /* File: default-constructor.cpp */
{
  private:
    int frequency;
    char* str; 
  public:
    Word() { frequency = 0; str = nullptr; } // Default constructor
};

int main() 
{ 
    Word movie; // No arguments => expect default constructor
}

This is a default constructor

If there is no default constructor, there will be an empty default constructor created by c++

class Word              /* File: default-constructor-bug.cpp */
{ 
  private: int frequency; char* str;
  public: Word(const char* s, int k = 0);
};

int main() { Word movie; }	// which constructor?

Since the default constructor is not implemented, there will be error

Conversion

Conversion constructor is a constructor passing a single parameter

#include <cstring>    /* File: implicit-conversion-constructor.cpp */
class Word
{ 
  private: int frequency; char* str;
  public:
    Word(char c)
        { frequency = 1; str = new char[2]; str[0] = c; str[1] = '\\0'; }
    Word(const char* s) // Assumption: s != nullptr
        { frequency = 1; str = new char [strlen(s)+1]; strcpy(str, s); }
};

int main() 
{
    Word movie("Titanic");              // Explicit conversion
    Word movie2 {'A'};                  // Explicit conversion
    Word movie3 = 'B';                  // Implicit conversion
    Word director = "James Cameron";    // Implicit conversion
}

Implicit: using more resourses(type conversion?)

#include <iostream>     /* File: implicit-conversion-surprise.cpp */
#include <cstring> 
using namespace std;
class Word
{
  private:
    int frequency; char* str;
  public:
    Word(char c)
        { frequency = 1; str = new char[2]; str[0] = c; str[1] = '\\0';
          cout << "call char conversion\\n"; }
    Word(const char* s)
        { frequency = 1; str = new char [strlen(s)+1]; strcpy(str, s);
          cout << "call const char* conversion\\n"; }
    void print() const { cout << str << " : " << frequency << endl; }
};

void print_word(Word x) { x.print(); }
int main() { print_word("Titanic"); print_word('A'); return 0; }

Input a string to the global function argument

explicit Word(const char* s)
        { frequency = 1; str = new char [strlen(s)+1]; strcpy(str, s);
          cout << "call const char* conversion\\n"; }

If you wish this not happening, add an ‘explicit’ keyword