简体   繁体   中英

Promotion Constructor in C++

What is promotion constructor? does it have any relation with copy constructor/assignment operator? I have seen one example however unable to understand that.

#include <iostream>
#include <vector>

using namespace std;

class base{
    public:
    base(){
        cout << endl << "base class default construtor" << endl;
    }
    base(const base& ref1){
        cout << endl << "base class copy constructor" << endl;
    }
    base(int) { 
        cout << endl << "base class promotion constructor" << endl;
    }
};

class derived : public base{
    public:
        derived(){
            cout << endl << "derived class default constructor" << endl;
        }
        derived(const derived& ref2){
            cout << endl << "derived class copy constructor" << endl;
        }
        derived(int) {
            cout << endl << "derived class promotion constructor" << endl;
        }
};

int main(){

    vector<base> vect;
    vect.push_back(base(1));
    vect.push_back(base(1));
    vect.push_back(base(2));

    return 0;
}

When I compile and execute: than the order has come like this:

base class promotion constructor

base class copy constructor

base class promotion constructor

base class promotion constructor

base class copy constructor

base class promotion constructor

base class promotion constructor

base class copy constructor

base class promotion constructor

Please help me to understand this concept of promotion constructor. I have searched on net however didn't get much info on this.

Thanks

First time I ever heard the term "promotion constructor". Both constructors that are named that way in your code fit the definiton of a converting constructor .

What is promotion constructor?

It's not a standard term in C++. Promotion refers to some of the type conversions applied automatically to built-in numeric types, and doesn't involve classes or constructors.

The constructors in your example are converting constructors : non-explicit constructors taking a single parameter, which can be used to convert that parameter type into the class type.

Being non-explicit, they can be used both for explicit conversions, like the base(1) in your example, and implicit conversions, like

vect.push_back(42);

which your example doesn't demonstrate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM