Q:

Can one constructor of a class call another constructor of the same class to initialize this object?

0

Can one constructor of a class call another constructor of the same class to initialize this object?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

Onward C++11  Yes, let see an example,

#include <iostream>
using namespace std;
class Test
{
    int a, b;
public:
    Test(int x, int y)
    {
        a= x;
        b =y;
    }
    Test(int y) : Test( 7, y) {}
    void displayXY()
    {
        cout <<"a = "<<a<<endl;
        cout <<"b = "<<b<<endl;
    }
};
int main()
{
    Test obj(27);
    obj.displayXY();
    return 0;
}

Output:

a = 7
b = 27

Note: Using some tricks you can also do in C++03. If you want to know how or know the answer then please write in the comment box.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions For Experienced

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Can a copy constructor accept an object of the sam... >>
<< Why copy constructor argument should be const in C...