Can you call a constructor from another constructor in C++? (Constructor chaining)
Hello, colleagues! I'm a beginner C++ developer and I've encountered a problem that seems very strange to me. I have a class with several constructors. They all do the same thing: initialize fields, allocate memory, but with different parameters. For example, one constructor takes a name and age, another takes only a name (age defaults to 0), and a third takes nothing (all defaults).
\n\nHere's a simplified code of what I'm trying to do:
\n\nclass Person {\npublic:\n std::string name;\n int age;\n\n // Constructor with two parameters\n Person(const std::string& n, int a) : name(n), age(a) {\n // some complex initialization, e.g., age validation\n if (age < 0) age = 0;\n std::cout << "Person created: " << No answers yet.
Log in to leave an answer