Articles & Books

Quick Q: How do C++ class members get initialized if I don't do it explicitly?

Quick A: default constructors are called if available, otherwise there is no initialisation.

Recently on SO:

How do C++ class members get initialized if I don't do it explicitly?

In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions.

For objects, their default constructor is called. For example, for std::string, the default constructor sets it to an empty string. If the object's class does not have a default constructor, it will be a compile error if you do not explicitly initialize it.

For primitive types (pointers, ints, etc), they are not initialized -- they contain whatever arbitrary junk happened to be at that memory location previously.

For references (e.g. std::string&), it is illegal not to initialize them, and your compiler will complain and refuse to compile such code. References must always be initialized.

So, in your specific case, if they are not explicitly initialized:

    int *ptr;  // Contains junk
    string name;  // Empty string
    string *pname;  // Contains junk
    string &rname;  // Compile error
    const string &crname;  // Compile error
    int age;  // Contains junk

fixing c++ with epochs -- Vittorio Romeo

This article proposes a mechanism to allow seemingly backwards-incompatible changes to C++'s syntax while actually maintaining backwards compatibility, leveraging the isolation of upcoming module units. The idea is similar to Rust's "Editions" mechanism. The post explains how the feature would work and how C++ would benefit from it.

fixing c++ with epochs

by Vittorio Romeo

From the article:

Imagine that you have been designing a programming language for over 30 years and that it gradually became widely used across the globe. Some of the decisions you made at the beginning were excellent and contributed to the success of your project. Some others, however, were not the best: over the years you and your users realized that the world would have been a better place if those choices you made eons ago were slightly different. [...]

What if I told you that I could fix all of your problems? Even better, what if I told you that backward-compatibility will never be broken and that migration to newer versions of your language could be automated?

CppCon Advice

Don't miss it out.

CppCon Advice

From the article:

Hello all, I've been programming in C++ for about 5 years now, 4 years in a university setting and 1 at my current employer. Recently, I put in a request to attend CppCon and it was accepted, which I'm thrilled about...