Without initialzation lists a member object gets first instantiated with its default constructor and after that the assignment operator is used.

Without initialization lists

class Cat {
public:
    Cat() {
        std::cout << "Cat constructor called." << std::endl;
    }
    Cat(const Cat& otherCat) {
        std::cout << "Copy constructor" << std::endl;
    }
    Cat& operator=(const Cat& rhs) {
        std::cout << "Assignment operator used." << std::endl;
        return *this;
    }
};

class Zoo {
    Cat tiger;
public:
    Zoo(const Cat& cat) {
        tiger = cat;
    }
};

int main() {
    Cat cat;
    Zoo zoo(cat);
    return 0;
}
Cat constructor called.
Cat constructor called. //inside Zoo
Assignment operator used.

With initialization lists

With initialization lists only the copy constructor is called. Thus better performance.

class Zoo {
    Cat tiger;
public:
    Zoo(const Cat& cat) :tiger(cat) {};
};

int main() {
    Cat cat;
    Zoo zoo(cat);
    return 0;
}
Cat constructor called.
Copy constructor

Categories: