I have following code
#include <iostream>
using namespace std;
class Base {
private:
Base() {
cout<<"Base ctor has been called "<<endl;
};
public:
int a;
};
class Derived: public Base {
};
int main() {
Base* b1;
Derived d1();
cout<<d1;
return 0;
}
I am not sure how the derived class object d1 is created in the above example. The code compiles and run without any error. What type of constructor is getting called while creating Derived d1();
? and why output of the cout<<d1;
is coming as 1? Would the instance of Derived have int a
of base class? Thanks for all the help!
Inside your main
function, Derived d1();
is actually a declaration of a function called d1
that takes no arguments and returns a Derived
. As for why this prints 1
, std::ostream
has no overload for a Derived (*)()
(which d1
is implicitly converted to) so it converts it to the only suitable type, which is a bool
. Try replacing cout<<d1;
with cout << boolalpha << d1;
and you'll see that the program prints true
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.