Main Content

Copy constructor not called in initialization list

Copy constructor does not call copy constructors of some members or base classes

Description

This defect occurs when the copy constructor of a class does not call the copy constructor of the following in its initialization list:

  • One or more of its members.

  • Its base classes when applicable.

    The defect occurs even when a base class constructor is called instead of the base class copy constructor.

Risk

The calls to the copy constructors can be done only from the initialization list. If the calls are missing, it is possible that an object is only partially copied.

  • If the copy constructor of a member is not called, it is possible that the member is not copied.

  • If the copy constructor of a base class is not called, it is possible that the base class members are not copied.

Fix

If you want your copy constructor to perform a complete copy, call the copy constructor of all members and all base classes in its initialization list.

Examples

expand all

class Base {
public:
    Base();
    Base(int);
    Base(const Base&);
    virtual ~Base();
private:
    int ib;
};

class Derived:public Base {
public:
    Derived();
    ~Derived();
    Derived(const Derived& d): Base(), i(d.i) { }
private:
    int i;
};

In this example, the copy constructor of class Derived calls the default constructor, but not the copy constructor of class Base.

The defect appears on the : symbol in the copy constructor definition. Following are some tips for navigating in the source code:

  • To navigate to the class definition, right-click a member that is initialized in the constructor. Select Go To Definition. In the class definition, you see the class members, including those members whose copy constructors are not called.

  • To navigate to a base class definition, first navigate to the derived class definition. In the derived class definition, where the derived class inherits from a base class, right-click the base class name and select Go To Definition.

Correction — Call Base Class Copy Constructor

One possible correction is to call the copy constructor of class Base from the initialization list of the Derived class copy constructor.

class Base {
public:
    Base();
    Base(int);
    Base(const Base&);
    virtual ~Base();
private:
    int ib;
};

class Derived:public Base {
public:
    Derived();
    ~Derived();
    Derived(const Derived& d): Base(d), i(d.i) { }
private:
    int i;
};

Result Information

Group: Object oriented
Language: C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: MISSING_COPY_CTOR_CALL
Impact: High

Version History

Introduced in R2015b