Each time you assign an instance of the variable ob
of type B
an integer value, you are basically constructing a new instance of B
thus calling the constructor. Think about it, how else would the compiler know how to create an instance of B
if not through the constructor taking an int
as parameter?
If you overloaded the assignment operator for your class B
taking an int
, it would be called:
B& operator=(int rhs)
{
cout << "Assignment operator" << endl;
}
This would result in the first line: B ob = 5;
to use the constructor, while the two following would use the assignment operator, see for yourself:
Constructor called
Assignment operator
Assignment operator
http://ideone.com/fAjoA4
If you do not want your constructor taking an int
to be called upon assignment, you can declare it explicit
like this:
explicit B(int x)
{
cout << "Constructor called" << endl;
}
This would cause a compiler error with your code, since it would no longer be allowed to implicitly construct an instance of B
from an integer, instead it would have to be done explicitly, like this:
B ob(5);
On a side note, your constructor taking an int
as parameter, is not a default constructor, a default constructor is a constructor which can be called with no arguments.