Is it possible to call one constructor from another in C++ (constructor chaining)?
Hello everyone! I just started learning C++ after Java and ran into a problem. In Java, I often did this:
```java
public class MyClass {
private int x;
private int y;
public MyClass() {
this(0, 0); // calling constructor with parameters
}
public MyClass(int x, int y) {
this.x = x;
this.y = y;
}
}
```
Now I'm trying to do the same in C++:
```cpp
class MyClass {
private:
int x;
int y;
public:
MyClass() {
MyClass(0, 0); // is this not allowed?
}
MyClass(int x, int y) {
this->x = x;
this->y = y;
}
};
```
But it doesn't work! In the default constructor, a temporary object is created which is immediately destroyed, and the fields of the current object remain uninitialized. How to p
No answers yet.
Log in to leave an answer
Blogs
Concurrency and Multithreading in Go: A Complete Guide for Developers
How to Get Hired as a TypeScript Developer: Tips and a Resume in Practice
PHP for Machine Learning: Possibilities and Limitations for Beginners
Career of a TypeScript Developer: Myths, Truth, and Million-Dollar Code