Class and Struct Constructors

beginner c++11 classes

Classes and structs have initialization functions called constructors in C++. Constructors are used to initialize a class’s internal state, whatever that may be. Constructors are special functions that share the name of their class and require no explicit return statement because in calling code it’s the object that’s being constructed that’s returned.

C++ compilers can generate constructors for you when they are simple enough. If fields can be initialized with a simple constant you can assign them right in the class’s declaration. Here’s an example:

#include <iostream>
#include <string>

class Person {
public:
  int age = 25;
  std::string name = "Unknown";
};

int main() {
  // These both call the constructor of Person
  Person person;
  Person person2 = Person();
  std::cout << person.name << " is " << person.age << "\n";
  std::cout << person2.name << " is " << person2.age << "\n";
}
Unknown is 25
Unknown is 25

Custom Constructors

A class or struct can have as many constructors as you’d like. Constructors are very similar to regular functions and can have parameters as well. If a parameter is to be used to initialize a class member, you can assign that parameter in a special member initializer list.

If you write custom constructors C++ will no longer create the default constructor for you. You can tell C++ to implement the default constructor with the = default keyword. Here’s an example:

#include <iostream>
#include <string>

class Person {
public:
  // We need this now because of the custom constructors
  Person() = default;
  Person(int age) : age(age) {
  }
  Person(int age, std::string name) 
    : age(age), name(std::move(name)) {
  }

  int age = 25;
  std::string name = "Unknown";
};

int main() {
  Person person;
  std::cout << person.name << " is " << person.age << "\n";

  Person person2 = Person(40);
  std::cout << person2.name << " is " << person2.age << "\n";

  Person person3 = Person(33, "Johnny");
  std::cout << person3.name << " is " << person3.age << "\n";
}
Unknown is 25
Unknown is 40
Johnny is 33

Constructor Errors

If a class’s constructor can’t initialize its internal state, if there’s been an error, the only way to report that in C++ is to throw an exception. A good example is managing “resources”, like files. Note that this is just an example, the C++ Standard Library has file classes for reading and writing files.

#include <iostream>
#include <string>
#include <exception>
#include <stdio.h>

// A low-level File class
class File {
public:
  File(const std::string& path, const std::string& mode) {
    file_ = fopen(path.c_str(), mode.c_str());
    if (!file_) {
      throw std::runtime_error("Failed to open " + path + 
                               " with mode " + mode);      
    }
  }

  ~File() {
    fclose(file_);
  }
private:
  FILE* file_;
};

int main() {
  try {
    File file("some_path_of_a_file_that_isnt_here", "r");
  } catch (const std::exception& e) {
    std::cout << e.what();
  }
}
Failed to open some_path_of_a_file_that_isnt_here with mode r


For more C++ By Example, click here.