0
    #include<iostream>
using namespace std;

class A {
 public:
    A(int ii = 0) : i(ii) {}
    void show() { cout << "i = " << i << endl;}
 private:
    int i;
};

class B {
 public:
    B(int xx) : x(xx) {}
    operator A() const { return A(x); }
 private:
    int x;
};

void g(A a)
{  a.show(); }

int main() {
  B b(10);
  g(b);
  g(20);
  getchar();
  return 0;
} 

In the above code can anyone explain what does the line

A(int ii = 0) : i(ii) {}

mean and how the output of the program

i = 10
i = 20
John Kugelman
  • 330,190
  • 66
  • 504
  • 555
iec2011007
  • 1,700
  • 3
  • 21
  • 35

3 Answers3

2
A(int ii = 0) : i(ii) {}

is class A's constructor, and constructor has a value ii, and initializing i to ii.

Output

B b(10);
g(b);
g(20);

in this code, g(20) is pass temporary instance of class B.

because, the class B's constructor is not explicit so int to B is OK.

Joy Hyuk Lee
  • 716
  • 9
  • 22
  • Sorry sir, did not understand why g(20) is not an error ?? – iec2011007 Sep 13 '14 at 18:29
  • You need to understand c++ constructor. B'c constructor's parameter is int. So you pass int, than compiler can find B's Constructor. And automacally call B's constructor. – Joy Hyuk Lee Sep 13 '14 at 18:30
  • But A's Constructor also has int as the parameter ?? – iec2011007 Sep 13 '14 at 18:31
  • Oops. My mistake. But also class A's constructor has int. so if you pasa int, compiler will call A's conatructor. – Joy Hyuk Lee Sep 13 '14 at 18:33
  • Just one more question what does the line operator A() const { return A(x); } mean ?? and why can g function accept and object of class B ?? – iec2011007 Sep 13 '14 at 18:34
  • 2
    operator mean Implicitlly converting B to A. So, when you pasa B class to g function, B's converting functions has called. So you can use B instance. PS. I'm not sir i just 14 years old programmer: ) – Joy Hyuk Lee Sep 13 '14 at 18:44
  • Is this answer helpful? Than accept this answer please! – Joy Hyuk Lee Sep 13 '14 at 19:02
0

This is declaring the constructor to class A

A(int ii = 0) : i(ii) {}

This part declares that the constructor can take a single int parameter, that has a default value of 0.

A(int ii = 0)

This part is initializing the member variable i with the value from the parameter ii.

i(ii)
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201
0

A(int ii = 0) : i(ii) {}

is the constructor of class A and it takes an argument ii, which in the initializer list, is assigned to i. Then the body of it does nothing.

Equivalently you have:

A(int ii = 0) : i(ii) {
 // do nothing
}

Equivalently -in terms of result- you have:

A(int ii = 0) {
  i = ii;
}
gsamaras
  • 69,751
  • 39
  • 173
  • 279