I always think I know C++ pretty well, but sometimes I'm surprised by even the most fundamental things.
In the following scenario, I'm confused as to why the constructor Derived::Derived(const Base&)
is invoked:
class Base
{ };
class Derived : public Base
{
public:
Derived() { }
Derived(const Base& b)
{
std::cout << "Called Derived::Derived(const Base& b)" << std::endl;
}
};
int main()
{
Derived d;
Base b;
d = b;
}
This outputs: Called Derived::Derived(const Base& b)
, indicating that the second constructor in Derived
was invoked. Now, I thought I knew C++ pretty well, but I can't figure out why that constructor would be invoked. I understand the whole "rule of four" concept, and I would think that the expression d = b
would do one of two things: Either it would 1) invoke the implicit (compiler-generated) assignment operator of Base
, or 2) Trigger a compiler error complaining that the function Derived& operator = (const Base&)
does not exist.
Instead, it called a constructor, even though the expression d = b
is an assignment expression.
So why does this happen?
What is constructor? A constructor is a special type of member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object (instance of class) create. It is special member function of the class because it does not have any return type. How constructors are different from a normal member ...
A confusion matrix is a summary of prediction results on a classification problem. The number of correct and incorrect predictions are summarized with count values and broken down by each class. This is the key to the confusion matrix.
Whenever we define one or more non-default constructors ( with parameters ) for a class, a default constructor ( without parameters ) should also be explicitly defined as the compiler will not provide a default constructor in this case. However, it is not necessary but it’s considered to be the best practice to always define a default constructor.
A constructor is different from normal functions in following ways: Constructor has same name as the class itself Constructors don’t have return type A constructor is automatically called when an object is created. If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).
d = b can happen because b is converted to Derived. The second constructor is used for automatic type conversion. It's like d = (Derived) b
Derived isa Base, but Base isn'ta Derived, so it has to be converted before assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With