example4_explicit_constructor_call.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

class Person {
public:
    explicit Person(const std::string& name) : name_(name) {}
    void introduce() const { std::cout << "My name is " << name_ << std::endl; }

private:
    std::string name_;
};

int main() {
    std::string name = "Alice";
    
    // Using static_cast to call explicit constructor
    Person person = static_cast<Person>(name);
    person.introduce();

    return 0;
}
Back to static_cast