samedi 30 janvier 2016

Questions about a piece of code with templates, conversion operator and copy ctor

Two questions about the following piece of code:

template <class T> class A {
protected:
    T j;
public:
    A(T k) :j(k) {cout << *this;}
    ~A() { cout << *this; }
    A(const A<T> &a) {
        j = a.j;
        cout << *this;
    }
    virtual void print() const {cout << j << ' ';}

    friend ostream &operator << (ostream &os, const A<T> &a) {
        a.print();
        return os;
    }
    operator T() {  return j;}
};

template <class T> class inherit:public A<T> {
    T field;
public:
    inherit(const T&t) :A<T>(t), field(1+t) {
        cout << *this;
    }
    void print() const {
        A<T>::print();
        cout << field << ' ';
    }
};
int main(){
    inherit <int> b(3);

    inherit <string> c("asdf");
    string k="str";
    c + k;//error no operator +
    b + 5;//no error
}

  1. Why does inherit <int> b(3); leads to the copy ctor of inherit? Why copy instead of making a new instance of inherit from scratch using the default ctor?

  2. Why does b+5; leads to the conversion operator operator T() and why it doesn't happen with c+k?

Aucun commentaire:

Enregistrer un commentaire