-3

Why is the constructor H1 and H2 getting called? Can I get the reason?

class A
{
public:
    int a;
    char b;

    A()
    {
        a = 0;
        b = '\n';
    }

    A(int a)
    {
        cout << "H1";
    }

    A(char c)
    {
        cout << "H2";
    }
};

int main()
{
    int a = 10;
    char c = 'h';
    A ob1 = a;
    ob1 = c;
}
David G
  • 94,763
  • 41
  • 167
  • 253
RIshab R Bafna
  • 397
  • 1
  • 3
  • 7
  • It is unclear why you expect it not to be called. – sashoalm Aug 19 '14 at 16:30
  • See here: http://stackoverflow.com/a/121163/2721883 – clcto Aug 19 '14 at 16:31
  • @ScottLawson SSCCEs aren't supposed to do anything http://sscce.org/ they just show a simple example of a concept. The question shows a lack of understanding but at the same time C++ is a complex language with a LOT of tutorials about a LOT of different subjects. A pointer as to what tutorials might help would be more useful. – Philip Couling Aug 19 '14 at 16:43
  • @couling agree, basic questions should be answered insightfully – BeyelerStudios Aug 19 '14 at 16:45

2 Answers2

4
A ob1 = a;

This initialises an object of type A from an int value. That uses the constructor A(int), printing H1.

ob1 = c;

This assigns a char value to the object. Since there isn't a suitable assignment operator A::operator=(char), which could assign the value directly, it does this in two stages:

  • Create a temporary object of type A from the char value
  • Assign that to ob1 using the implicit copy-assignment operator.

The first stage initialises the temporary using the constructor A(char), printing H2.

Hence, the output is H1H2.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0
class A {
  public:
    int a;
    char b;
    A() {
            a=0;
            b='\n'; 
    }
    A(int a) {
           cout<<"H1";
    }
    A(char c) {
           cout<<"H2";
    } 
}; 

int main() {
    int a=10;
    char c='h';
    A ob1=a; // calls A(int a) because a is typeof int
    ob1=c;  // calls A(char c) because c is typeof char
}
Marco
  • 7,007
  • 2
  • 19
  • 49