Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

c++ - constructor of base class works but its effect gets cancelled

I have the following code:

item.h

using item_t = char;
    
constexpr item_t no_item = '*';
constexpr item_t item1 = 'a';
constexpr item_t item2 = 'b';
    
bool isItem(const item_t &item) {
    return item == no_item || item == item1 || item == item2;
}
        
class base {
public:
    base() : value(no_item) {}
    base(const item_t &item) : value(item) {}
    friend std::ostream &operator<<(std::ostream &out, const base &b) {
        out << b.value;
    }
    /*other stuff*/
private:
    item_t value;
};
                
template<bool(*check)(const item_t&)> 
class derivedTmp : base {
public:
    derivedTmp() : base() {}
    derivedTmp(item_t item) {
        if (!check(item)) {
            base::base();
        }
        else {
            base::base(item);
        }
    }
};

using derived = derivedTmp<isItem>;
const derived d1(item1);
const derived d2(item2);

main.cpp

#include<iostream>
#include "item.h"
    
int main() {
    cout << item1 << "" << item2 << "
";
}

I really do not understand why it does not work. If there is some syntax error, it doesn't care because it means I made a mistake but the program compiles good; the output is * * instead of a b as I expect. Can anyone explain to me why? I’m using C++17 in Visual Studio 19.

question from:https://stackoverflow.com/questions/65856244/constructor-of-base-class-works-but-its-effect-gets-cancelled

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const derived d1(item1);

The above invokes derivedTmp(item_t item) constructor.

This will first invoke the default base constructor which is base::base() which sets value to no_item i.e. '*'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...